dev: chg: regression changes for bor after merge

This commit is contained in:
marcello33 2023-06-12 16:46:03 +02:00
parent a043ec6d62
commit 162af07d38
54 changed files with 1072 additions and 705 deletions

View file

@ -83,8 +83,7 @@ func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.Genesis
GasLimit: gasLimit,
Alloc: alloc,
}
genesis.MustCommit(database)
blockchain, _ := core.NewBlockChain(database, nil, &genesis, ethash.NewFaker(), vm.Config{}, nil, nil, nil)
blockchain, _ := core.NewBlockChain(database, nil, &genesis, nil, ethash.NewFaker(), vm.Config{}, nil, nil, nil)
backend := &SimulatedBackend{
database: database,
@ -670,7 +669,7 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallM
evmContext := core.NewEVMBlockContext(header, b.blockchain, nil)
vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{NoBaseFee: true})
gasPool := new(core.GasPool).AddGas(math.MaxUint64)
return core.ApplyMessage(vmEnv, *msg, gasPool, context.Background())
return core.ApplyMessage(vmEnv, msg, gasPool, context.Background())
}
// SendTransaction updates the pending block to include the given transaction.

View file

@ -86,7 +86,7 @@ checkpoint-admin status --rpc <NODE_RPC_ENDPOINT>
### Enable checkpoint oracle in your private network
Currently, only the Ethereum mainnet and the default supported test networks (rinkeby, goerli) activate this feature. If you want to activate this feature in your private network, you can overwrite the relevant checkpoint oracle settings through the configuration file after deploying the oracle contract.
Currently, only the Ethereum mainnet and the default supported test networks (goerli) activate this feature. If you want to activate this feature in your private network, you can overwrite the relevant checkpoint oracle settings through the configuration file after deploying the oracle contract.
* Get your node configuration file `geth dumpconfig OTHER_COMMAND_LINE_OPTIONS > config.toml`
* Edit the configuration file and add the following information

View file

@ -44,7 +44,7 @@ set to standard output. The following filters are supported:
- `-limit <N>` limits the output set to N entries, taking the top N nodes by score
- `-ip <CIDR>` filters nodes by IP subnet
- `-min-age <duration>` filters nodes by 'first seen' time
- `-eth-network <mainnet/rinkeby/goerli/sepolia>` filters nodes by "eth" ENR entry
- `-eth-network <mainnet/goerli/sepolia>` filters nodes by "eth" ENR entry
- `-les-server` filters nodes by LES server support
- `-snap` filters nodes by snap protocol support

View file

@ -76,27 +76,6 @@ func TestSnapSuite(t *testing.T) {
}
}
func TestSnapSuite(t *testing.T) {
geth, err := runGeth()
if err != nil {
t.Fatalf("could not run geth: %v", err)
}
defer geth.Close()
suite, err := NewSuite(geth.Server().Self(), fullchainFile, genesisFile)
if err != nil {
t.Fatalf("could not create new test suite: %v", err)
}
for _, test := range suite.SnapTests() {
t.Run(test.Name, func(t *testing.T) {
result := utesting.RunTAP([]utesting.Test{{Name: test.Name, Fn: test.Fn}}, os.Stdout)
if result[0].Failed {
t.Fatal()
}
})
}
}
// runGeth creates and starts a geth node
func runGeth() (*node.Node, error) {
stack, err := node.New(&node.Config{

View file

@ -288,43 +288,3 @@ func (c *Conn) ReadSnap(id uint64) (Message, error) {
}
return nil, fmt.Errorf("request timed out")
}
// ReadSnap reads a snap/1 response with the given id from the connection.
func (c *Conn) ReadSnap(id uint64) (Message, error) {
respId := id + 1
start := time.Now()
for respId != id && time.Since(start) < timeout {
code, rawData, _, err := c.Conn.Read()
if err != nil {
return nil, fmt.Errorf("could not read from connection: %v", err)
}
var snpMsg interface{}
switch int(code) {
case (GetAccountRange{}).Code():
snpMsg = new(GetAccountRange)
case (AccountRange{}).Code():
snpMsg = new(AccountRange)
case (GetStorageRanges{}).Code():
snpMsg = new(GetStorageRanges)
case (StorageRanges{}).Code():
snpMsg = new(StorageRanges)
case (GetByteCodes{}).Code():
snpMsg = new(GetByteCodes)
case (ByteCodes{}).Code():
snpMsg = new(ByteCodes)
case (GetTrieNodes{}).Code():
snpMsg = new(GetTrieNodes)
case (TrieNodes{}).Code():
snpMsg = new(TrieNodes)
default:
//return nil, fmt.Errorf("invalid message code: %d", code)
continue
}
if err := rlp.DecodeBytes(rawData, snpMsg); err != nil {
return nil, fmt.Errorf("could not rlp decode message: %v", err)
}
return snpMsg.(Message), nil
}
return nil, fmt.Errorf("request timed out")
}

View file

@ -229,14 +229,10 @@ func ethFilter(args []string) (nodeFilter, error) {
switch args[0] {
case "mainnet":
filter = forkid.NewStaticFilter(params.MainnetChainConfig, params.MainnetGenesisHash)
case "rinkeby":
filter = forkid.NewStaticFilter(params.RinkebyChainConfig, params.RinkebyGenesisHash)
case "goerli":
filter = forkid.NewStaticFilter(params.GoerliChainConfig, params.GoerliGenesisHash)
case "sepolia":
filter = forkid.NewStaticFilter(params.SepoliaChainConfig, params.SepoliaGenesisHash)
case "ropsten":
filter = forkid.NewStaticFilter(params.RopstenChainConfig, params.RopstenGenesisHash)
case "bor-mumbai":
filter = forkid.NewStaticFilter(params.MumbaiChainConfig, params.MumbaiGenesisHash)
case "bor-mainnet":

View file

@ -12,7 +12,6 @@ First things first, the `faucet` needs to connect to an Ethereum network, for wh
- `-genesis` is a path to a file containing the network `genesis.json`. or using:
- `-goerli` with the faucet with Görli network config
- `-rinkeby` with the faucet with Rinkeby network config
- `-sepolia` with the faucet with Sepolia network config
- `-network` is the devp2p network id used during connection
- `-bootnodes` is a list of `enode://` ids to join the network through

View file

@ -86,7 +86,6 @@ var (
twitterTokenV1Flag = flag.String("twitter.token.v1", "", "Bearer token to authenticate with the v1.1 Twitter API")
goerliFlag = flag.Bool("goerli", false, "Initializes the faucet with Görli network config")
rinkebyFlag = flag.Bool("rinkeby", false, "Initializes the faucet with Rinkeby network config")
sepoliaFlag = flag.Bool("sepolia", false, "Initializes the faucet with Sepolia network config")
mumbaiFlag = flag.Bool("bor-mumbai", false, "Initializes the faucet with Bor-Mumbai network config")
)
@ -141,7 +140,7 @@ func main() {
log.Crit("Failed to render the faucet template", "err", err)
}
// Load and parse the genesis block requested by the user
genesis, err := getGenesis(*genesisFlag, *goerliFlag, *rinkebyFlag, *sepoliaFlag, *mumbaiFlag)
genesis, err := getGenesis(*genesisFlag, *goerliFlag, *sepoliaFlag, *mumbaiFlag)
if err != nil {
log.Crit("Failed to parse genesis config", "err", err)
}
@ -888,7 +887,7 @@ func authNoAuth(url string) (string, string, common.Address, error) {
}
// getGenesis returns a genesis based on input args
func getGenesis(genesisFlag string, goerliFlag bool, rinkebyFlag bool, sepoliaFlag bool, mumbaiFlag bool) (*core.Genesis, error) {
func getGenesis(genesisFlag string, goerliFlag bool, sepoliaFlag bool, mumbaiFlag bool) (*core.Genesis, error) {
switch {
case genesisFlag != "":
var genesis core.Genesis
@ -896,8 +895,6 @@ func getGenesis(genesisFlag string, goerliFlag bool, rinkebyFlag bool, sepoliaFl
return &genesis, err
case goerliFlag:
return core.DefaultGoerliGenesisBlock(), nil
case rinkebyFlag:
return core.DefaultRinkebyGenesisBlock(), nil
case sepoliaFlag:
return core.DefaultSepoliaGenesisBlock(), nil
case mumbaiFlag:

View file

@ -26,6 +26,7 @@ import (
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/console"
"github.com/ethereum/go-ethereum/internal/flags"
"github.com/urfave/cli/v2"
)
var (
@ -125,18 +126,7 @@ func remoteConsole(ctx *cli.Context) error {
path = ctx.String(utils.DataDirFlag.Name)
}
if path != "" {
if ctx.Bool(utils.RopstenFlag.Name) {
// Maintain compatibility with older Geth configurations storing the
// Ropsten database in `testnet` instead of `ropsten`.
legacyPath := filepath.Join(path, "testnet")
if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
path = legacyPath
} else {
path = filepath.Join(path, "ropsten")
}
} else if ctx.Bool(utils.RinkebyFlag.Name) {
path = filepath.Join(path, "rinkeby")
} else if ctx.Bool(utils.GoerliFlag.Name) {
if ctx.Bool(utils.GoerliFlag.Name) {
path = filepath.Join(path, "goerli")
} else if ctx.Bool(utils.MumbaiFlag.Name) || ctx.Bool(utils.BorMainnetFlag.Name) {
homeDir, _ := os.UserHomeDir()
@ -148,7 +138,7 @@ func remoteConsole(ctx *cli.Context) error {
}
endpoint = fmt.Sprintf("%s/bor.ipc", path)
}
client, err := dialRPC(endpoint)
client, err := utils.DialRPCWithHeaders(endpoint, ctx.StringSlice(utils.HttpHeaderFlag.Name))
if err != nil {
utils.Fatalf("Unable to attach to remote geth: %v", err)
}

View file

@ -57,11 +57,6 @@ const (
)
var (
// Git SHA1 commit hash of the release (set via linker flags)
gitCommit = ""
gitDate = ""
// The app that holds all commands and flags.
app = flags.NewApp(gitCommit, gitDate, fmt.Sprintf("the %s command line interface", repositoryIdentifier))
// flags that configure the node
nodeFlags = flags.Merge([]cli.Flag{
utils.BorLogsFlag,
@ -113,7 +108,7 @@ var (
utils.UltraLightFractionFlag,
utils.UltraLightOnlyAnnounceFlag,
utils.LightNoSyncServeFlag,
utils.EthPeerRequiredBlocksFlag,
utils.EthRequiredBlocksFlag,
utils.LegacyWhitelistFlag,
utils.BloomFilterSizeFlag,
utils.CacheFlag,
@ -151,13 +146,10 @@ var (
utils.DeveloperFlag,
utils.DeveloperPeriodFlag,
utils.DeveloperGasLimitFlag,
utils.RopstenFlag,
utils.SepoliaFlag,
utils.RinkebyFlag,
utils.GoerliFlag,
utils.MumbaiFlag,
utils.BorMainnetFlag,
utils.KilnFlag,
utils.VMEnableDebugFlag,
utils.NetworkIdFlag,
utils.EthStatsURLFlag,
@ -219,6 +211,8 @@ var (
}
)
var app = flags.NewApp("the go-ethereum command line interface")
func init() {
// Initialize the CLI app and start Geth
app.Action = geth
@ -291,9 +285,6 @@ func main() {
func prepare(ctx *cli.Context) {
// If we're running a known preset, log it for convenience.
switch {
case ctx.IsSet(utils.RinkebyFlag.Name):
log.Info("Starting Geth on Rinkeby testnet...")
case ctx.IsSet(utils.GoerliFlag.Name):
log.Info("Starting Geth on Görli testnet...")
@ -331,7 +322,6 @@ func prepare(ctx *cli.Context) {
if ctx.String(utils.SyncModeFlag.Name) != "light" && !ctx.IsSet(utils.CacheFlag.Name) && !ctx.IsSet(utils.NetworkIdFlag.Name) {
// Make sure we're not on any supported preconfigured testnet either
if !ctx.IsSet(utils.SepoliaFlag.Name) &&
!ctx.IsSet(utils.RinkebyFlag.Name) &&
!ctx.IsSet(utils.GoerliFlag.Name) &&
!ctx.IsSet(utils.MumbaiFlag.Name) &&
!ctx.IsSet(utils.DeveloperFlag.Name) {

View file

@ -2,11 +2,10 @@ package utils
import (
"encoding/json"
"io/ioutil"
"github.com/ethereum/go-ethereum/eth/ethconfig"
"github.com/urfave/cli/v2"
"os"
"gopkg.in/urfave/cli.v1"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/log"
@ -19,39 +18,39 @@ var (
//
// HeimdallURLFlag flag for heimdall url
HeimdallURLFlag = cli.StringFlag{
HeimdallURLFlag = &cli.StringFlag{
Name: "bor.heimdall",
Usage: "URL of Heimdall service",
Value: "http://localhost:1317",
}
// WithoutHeimdallFlag no heimdall (for testing purpose)
WithoutHeimdallFlag = cli.BoolFlag{
WithoutHeimdallFlag = &cli.BoolFlag{
Name: "bor.withoutheimdall",
Usage: "Run without Heimdall service (for testing purpose)",
}
// HeimdallgRPCAddressFlag flag for heimdall gRPC address
HeimdallgRPCAddressFlag = cli.StringFlag{
HeimdallgRPCAddressFlag = &cli.StringFlag{
Name: "bor.heimdallgRPC",
Usage: "Address of Heimdall gRPC service",
Value: "",
}
// RunHeimdallFlag flag for running heimdall internally from bor
RunHeimdallFlag = cli.BoolFlag{
RunHeimdallFlag = &cli.BoolFlag{
Name: "bor.runheimdall",
Usage: "Run Heimdall service as a child process",
}
RunHeimdallArgsFlag = cli.StringFlag{
RunHeimdallArgsFlag = &cli.StringFlag{
Name: "bor.runheimdallargs",
Usage: "Arguments to pass to Heimdall service",
Value: "",
}
// UseHeimdallApp flag for using internall heimdall app to fetch data
UseHeimdallAppFlag = cli.BoolFlag{
UseHeimdallAppFlag = &cli.BoolFlag{
Name: "bor.useheimdallapp",
Usage: "Use child heimdall process to fetch data, Only works when bor.runheimdall is true",
}
@ -84,17 +83,17 @@ func getGenesis(genesisPath string) (*core.Genesis, error) {
// SetBorConfig sets bor config
func SetBorConfig(ctx *cli.Context, cfg *eth.Config) {
cfg.HeimdallURL = ctx.GlobalString(HeimdallURLFlag.Name)
cfg.WithoutHeimdall = ctx.GlobalBool(WithoutHeimdallFlag.Name)
cfg.HeimdallgRPCAddress = ctx.GlobalString(HeimdallgRPCAddressFlag.Name)
cfg.RunHeimdall = ctx.GlobalBool(RunHeimdallFlag.Name)
cfg.RunHeimdallArgs = ctx.GlobalString(RunHeimdallArgsFlag.Name)
cfg.UseHeimdallApp = ctx.GlobalBool(UseHeimdallAppFlag.Name)
cfg.HeimdallURL = ctx.String(HeimdallURLFlag.Name)
cfg.WithoutHeimdall = ctx.Bool(WithoutHeimdallFlag.Name)
cfg.HeimdallgRPCAddress = ctx.String(HeimdallgRPCAddressFlag.Name)
cfg.RunHeimdall = ctx.Bool(RunHeimdallFlag.Name)
cfg.RunHeimdallArgs = ctx.String(RunHeimdallArgsFlag.Name)
cfg.UseHeimdallApp = ctx.Bool(UseHeimdallAppFlag.Name)
}
// CreateBorEthereum Creates bor ethereum object from eth.Config
func CreateBorEthereum(cfg *eth.Config) *eth.Ethereum {
workspace, err := ioutil.TempDir("", "bor-command-node-")
func CreateBorEthereum(cfg *ethconfig.Config) *eth.Ethereum {
workspace, err := os.MkdirTemp("", "bor-command-node-")
if err != nil {
Fatalf("Failed to create temporary keystore: %v", err)
}

View file

@ -24,6 +24,7 @@ import (
"encoding/hex"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/trie"
"math"
"math/big"
"net/http"
@ -76,6 +77,7 @@ import (
"github.com/ethereum/go-ethereum/rpc"
pcsclite "github.com/gballet/go-libpcsclite"
gopsutil "github.com/shirou/gopsutil/mem"
"github.com/urfave/cli/v2"
)
// These are all the command line flags we support.
@ -132,7 +134,7 @@ var (
}
NetworkIdFlag = &cli.Uint64Flag{
Name: "networkid",
Usage: "Explicitly set network id (integer)(For testnets: use --rinkeby, --goerli, --sepolia instead)",
Usage: "Explicitly set network id (integer)(For testnets: use --goerli, --sepolia instead)",
Value: ethconfig.Defaults.NetworkId,
Category: flags.EthCategory,
}
@ -141,11 +143,6 @@ var (
Usage: "Ethereum mainnet",
Category: flags.EthCategory,
}
RinkebyFlag = &cli.BoolFlag{
Name: "rinkeby",
Usage: "Rinkeby network: pre-configured proof-of-authority test network",
Category: flags.EthCategory,
}
GoerliFlag = &cli.BoolFlag{
Name: "goerli",
Usage: "Görli network: pre-configured proof-of-authority test network",
@ -156,6 +153,14 @@ var (
Usage: "Sepolia network: pre-configured proof-of-work test network",
Category: flags.EthCategory,
}
MumbaiFlag = &cli.BoolFlag{
Name: "bor-mumbai",
Usage: "Mumbai network: pre-configured proof-of-stake test network",
}
BorMainnetFlag = &cli.BoolFlag{
Name: "bor-mainnet",
Usage: "Bor mainnet",
}
// Dev mode
DeveloperFlag = &cli.BoolFlag{
@ -437,6 +442,10 @@ var (
Value: ethconfig.Defaults.TxPool.Lifetime,
Category: flags.TxPoolCategory,
}
BorLogsFlag = &cli.BoolFlag{
Name: "bor.logs",
Usage: "Enable bor logs retrieval",
}
// Performance tuning settings
CacheFlag = &cli.IntFlag{
@ -998,7 +1007,7 @@ Please note that --` + MetricsHTTPFlag.Name + ` must be set to start the server.
var (
// TestnetFlags is the flag group of all built-in supported testnets.
TestnetFlags = []cli.Flag{
RinkebyFlag,
GoerliFlag,
SepoliaFlag,
}
@ -1025,9 +1034,6 @@ func init() {
// then a subdirectory of the specified datadir will be used.
func MakeDataDir(ctx *cli.Context) string {
if path := ctx.String(DataDirFlag.Name); path != "" {
if ctx.Bool(RinkebyFlag.Name) {
return filepath.Join(path, "rinkeby")
}
if ctx.Bool(GoerliFlag.Name) {
return filepath.Join(path, "goerli")
}
@ -1082,8 +1088,6 @@ func setBootstrapNodes(ctx *cli.Context, cfg *p2p.Config) {
urls = SplitAndTrim(ctx.String(BootnodesFlag.Name))
case ctx.Bool(SepoliaFlag.Name):
urls = params.SepoliaBootnodes
case ctx.Bool(RinkebyFlag.Name):
urls = params.RinkebyBootnodes
case ctx.Bool(GoerliFlag.Name):
urls = params.GoerliBootnodes
}
@ -1531,8 +1535,6 @@ func SetDataDir(ctx *cli.Context, cfg *node.Config) {
cfg.DataDir = ctx.String(DataDirFlag.Name)
case ctx.Bool(DeveloperFlag.Name):
cfg.DataDir = "" // unless explicitly requested, use memory databases
case ctx.Bool(RinkebyFlag.Name) && cfg.DataDir == node.DefaultDataDir():
cfg.DataDir = filepath.Join(node.DefaultDataDir(), "rinkeby")
case ctx.Bool(GoerliFlag.Name) && cfg.DataDir == node.DefaultDataDir():
cfg.DataDir = filepath.Join(node.DefaultDataDir(), "goerli")
case ctx.Bool(SepoliaFlag.Name) && cfg.DataDir == node.DefaultDataDir():
@ -1727,7 +1729,7 @@ func CheckExclusive(ctx *cli.Context, args ...interface{}) {
// SetEthConfig applies eth-related command line flags to the config.
func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) {
// Avoid conflicting network flags
CheckExclusive(ctx, MainnetFlag, DeveloperFlag, RinkebyFlag, GoerliFlag, SepoliaFlag)
CheckExclusive(ctx, MainnetFlag, DeveloperFlag, GoerliFlag, SepoliaFlag)
CheckExclusive(ctx, LightServeFlag, SyncModeFlag, "light")
CheckExclusive(ctx, DeveloperFlag, ExternalSignerFlag) // Can't use both ephemeral unlocked and external signer
if ctx.String(GCModeFlag.Name) == "archive" && ctx.Uint64(TxLookupLimitFlag.Name) != 0 {
@ -1871,22 +1873,6 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) {
}
cfg.Genesis = core.DefaultSepoliaGenesisBlock()
SetDNSDiscoveryDefaults(cfg, params.SepoliaGenesisHash)
case ctx.Bool(RinkebyFlag.Name):
log.Warn("")
log.Warn("--------------------------------------------------------------------------------")
log.Warn("Please note, Rinkeby has been deprecated. It will still work for the time being,")
log.Warn("but there will be no further hard-forks shipped for it.")
log.Warn("The network will be permanently halted in Q2/Q3 of 2023.")
log.Warn("For the most future proof testnet, choose Sepolia as")
log.Warn("your replacement environment (--sepolia instead of --rinkeby).")
log.Warn("--------------------------------------------------------------------------------")
log.Warn("")
if !ctx.IsSet(NetworkIdFlag.Name) {
cfg.NetworkId = 4
}
cfg.Genesis = core.DefaultRinkebyGenesisBlock()
SetDNSDiscoveryDefaults(cfg, params.RinkebyGenesisHash)
case ctx.Bool(GoerliFlag.Name):
if !ctx.IsSet(NetworkIdFlag.Name) {
cfg.NetworkId = 5
@ -2039,7 +2025,7 @@ func RegisterFilterAPI(stack *node.Node, backend ethapi.Backend, ethcfg *ethconf
})
stack.RegisterAPIs([]rpc.API{{
Namespace: "eth",
Service: filters.NewFilterAPI(filterSystem, isLightClient),
Service: filters.NewFilterAPI(filterSystem, isLightClient, ethconfig.Defaults.BorLogs),
}})
return filterSystem
}
@ -2209,8 +2195,6 @@ func MakeGenesis(ctx *cli.Context) *core.Genesis {
genesis = core.DefaultGenesisBlock()
case ctx.Bool(SepoliaFlag.Name):
genesis = core.DefaultSepoliaGenesisBlock()
case ctx.Bool(RinkebyFlag.Name):
genesis = core.DefaultRinkebyGenesisBlock()
case ctx.Bool(GoerliFlag.Name):
genesis = core.DefaultGoerliGenesisBlock()
case ctx.Bool(DeveloperFlag.Name):
@ -2225,6 +2209,10 @@ func MakeChain(ctx *cli.Context, stack *node.Node, readonly bool) (*core.BlockCh
gspec = MakeGenesis(ctx)
chainDb = MakeChainDatabase(ctx, stack, readonly)
)
config, _, err := core.SetupGenesisBlock(chainDb, trie.NewDatabase(chainDb), gspec)
if err != nil {
Fatalf("%v", err)
}
cliqueConfig, err := core.LoadCliqueConfig(chainDb, gspec)
if err != nil {
Fatalf("%v", err)
@ -2233,7 +2221,17 @@ func MakeChain(ctx *cli.Context, stack *node.Node, readonly bool) (*core.BlockCh
if ctx.Bool(FakePoWFlag.Name) {
ethashConfig.PowMode = ethash.ModeFake
}
engine := ethconfig.CreateConsensusEngine(stack, &ethashConfig, cliqueConfig, nil, false, chainDb)
configs := &ethconfig.Config{
Genesis: gspec,
HeimdallURL: ctx.String(HeimdallURLFlag.Name),
WithoutHeimdall: ctx.Bool(WithoutHeimdallFlag.Name),
HeimdallgRPCAddress: ctx.String(HeimdallgRPCAddressFlag.Name),
RunHeimdall: ctx.Bool(RunHeimdallArgsFlag.Name),
RunHeimdallArgs: ctx.String(RunHeimdallArgsFlag.Name),
UseHeimdallApp: ctx.Bool(UseHeimdallAppFlag.Name),
}
_ = CreateBorEthereum(configs)
engine := ethconfig.CreateConsensusEngine(stack, config, configs, &ethashConfig, cliqueConfig, nil, false, chainDb, nil)
if gcmode := ctx.String(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
}

View file

@ -17,6 +17,7 @@
package common
import (
"fmt"
"os"
"path/filepath"
)

View file

@ -356,7 +356,7 @@ func (beacon *Beacon) Finalize(chain consensus.ChainHeaderReader, header *types.
// assembling the block.
func (beacon *Beacon) FinalizeAndAssemble(ctx context.Context, chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt, withdrawals []*types.Withdrawal) (*types.Block, error) {
if !beacon.IsPoSHeader(header) {
return beacon.ethone.FinalizeAndAssemble(ctx, chain, header, state, txs, uncles, receipts)
return beacon.ethone.FinalizeAndAssemble(ctx, chain, header, state, txs, uncles, receipts, nil)
}
// TODO marcello isShangai?
shanghai := chain.Config().IsShanghai(header.Time)

View file

@ -388,11 +388,6 @@ func (c *Bor) verifyHeader(chain consensus.ChainHeaderReader, header *types.Head
return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, gasCap)
}
// If all checks passed, validate any special fields for hard forks
if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil {
return err
}
// All basic checks passed, verify cascading fields
return c.verifyCascadingFields(chain, header, parents)
}
@ -783,7 +778,7 @@ func (c *Bor) Prepare(chain consensus.ChainHeaderReader, header *types.Header) e
// Finalize implements consensus.Engine, ensuring no uncles are set, nor block
// rewards given.
func (c *Bor) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, _ []*types.Transaction, _ []*types.Header) {
func (c *Bor) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, _ []*types.Transaction, _ []*types.Header, withdrawals []*types.Withdrawal) {
var (
stateSyncData []*types.StateSyncData
err error
@ -859,7 +854,7 @@ func (c *Bor) changeContractCodeIfNeeded(headerNumber uint64, state *state.State
// FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set,
// nor block rewards given, and returns the final block.
func (c *Bor) FinalizeAndAssemble(ctx context.Context, chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
func (c *Bor) FinalizeAndAssemble(ctx context.Context, chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt, withdrawals []*types.Withdrawal) (*types.Block, error) {
finalizeCtx, finalizeSpan := tracing.StartSpan(ctx, "bor.FinalizeAndAssemble")
defer tracing.EndSpan(finalizeSpan)

View file

@ -59,8 +59,7 @@ func TestGenesisContractChange(t *testing.T) {
statedb, err := state.New(genesis.Root(), state.NewDatabase(db), nil)
require.NoError(t, err)
config := params.ChainConfig{}
chain, err := core.NewBlockChain(db, nil, &config, b, vm.Config{}, nil, nil, nil)
chain, err := core.NewBlockChain(rawdb.NewMemoryDatabase(), nil, genspec, nil, b, vm.Config{}, nil, nil, nil)
require.NoError(t, err)
addBlock := func(root common.Hash, num int64) (common.Hash, *state.StateDB) {
@ -68,12 +67,12 @@ func TestGenesisContractChange(t *testing.T) {
ParentHash: root,
Number: big.NewInt(num),
}
b.Finalize(chain, h, statedb, nil, nil)
b.Finalize(chain, h, statedb, nil, nil, nil)
// write state to database
root, err := statedb.Commit(false)
require.NoError(t, err)
require.NoError(t, statedb.Database().TrieDB().Commit(root, true, nil))
require.NoError(t, statedb.Database().TrieDB().Commit(root, true))
statedb, err := state.New(h.Root, state.NewDatabase(db), nil)
require.NoError(t, err)

View file

@ -99,7 +99,7 @@ type Engine interface {
// Note: The block header and state database might be updated to reflect any
// consensus rules that happen at finalization (e.g. block rewards).
FinalizeAndAssemble(ctx context.Context, chain ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction,
uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error)
uncles []*types.Header, receipts []*types.Receipt, withdrawals []*types.Withdrawal) (*types.Block, error)
// Seal generates a new sealing request for the given input block and pushes
// the result into the given channel.

View file

@ -18,7 +18,6 @@ package ethash
import (
"context"
"io/ioutil"
"math/big"
"math/rand"
"os"

View file

@ -22,6 +22,7 @@ import (
"context"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/rlp"
"io"
"math/big"
"os"
@ -33,7 +34,6 @@ import (
"sync/atomic"
"time"
lru "github.com/hashicorp/golang-lru"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
@ -238,7 +238,7 @@ type BlockChain struct {
vmConfig vm.Config
// Bor related changes
borReceiptsCache *lru.Cache // Cache for the most recent bor receipt receipts per block
borReceiptsCache *lru.Cache[common.Hash, []*types.Receipt] // Cache for the most recent bor receipt receipts per block
stateSyncData []*types.StateSyncData // State sync data
stateSyncFeed event.Feed // State sync feed
chain2HeadFeed event.Feed // Reorg/NewHead/Fork data feed
@ -278,8 +278,6 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis
log.Info(strings.Repeat("-", 153))
log.Info("")
borReceiptsCache, _ := lru.New(receiptsCacheLimit)
bc := &BlockChain{
chainConfig: chainConfig,
cacheConfig: cacheConfig,
@ -297,10 +295,9 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis
engine: engine,
vmConfig: vmConfig,
borReceiptsCache: borReceiptsCache,
borReceiptsCache: lru.NewCache[common.Hash, []*types.Receipt](receiptsCacheLimit),
}
bc.flushInterval.Store(int64(cacheConfig.TrieTimeLimit))
// TODO marcello checker must be there
bc.forker = NewForkChoice(bc, shouldPreserve, checker)
bc.stateCache = state.NewDatabaseWithNodeDB(bc.db, bc.triedb)
bc.validator = NewBlockValidator(chainConfig, bc, engine)
@ -1539,11 +1536,11 @@ func (bc *BlockChain) writeBlockAndSetHead(ctx context.Context, block *types.Blo
var reorg bool
tracing.Exec(writeBlockAndSetHeadCtx, "", "blockchain.ReorgNeeded", func(_ context.Context, span trace.Span) {
reorg, err = bc.forker.ReorgNeeded(currentBlock.Header(), block.Header())
reorg, err = bc.forker.ReorgNeeded(currentBlock, block.Header())
tracing.SetAttributes(
span,
attribute.Int("number", int(block.Number().Uint64())),
attribute.Int("current block", int(currentBlock.Number().Uint64())),
attribute.Int("current block", int(currentBlock.Number.Uint64())),
attribute.Bool("reorg needed", reorg),
attribute.Bool("error", err != nil),
)
@ -1552,7 +1549,6 @@ func (bc *BlockChain) writeBlockAndSetHead(ctx context.Context, block *types.Blo
return NonStatTy, err
}
tracing.Exec(writeBlockAndSetHeadCtx, "", "blockchain.reorg", func(_ context.Context, span trace.Span) {
if reorg {
// Reorganise the chain if the parent is not the head block
@ -2407,8 +2403,6 @@ func (bc *BlockChain) reorg(oldHead *types.Header, newHead *types.Block) error {
}
}
log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "oldblocks", len(oldChain), "newnum", newBlock.Number(), "newhash", newBlock.Hash(), "newblocks", len(newChain))
}
// Insert the new chain(except the head block(reverse order)),
@ -2526,7 +2520,6 @@ func ExportN(w io.Writer, blocks []*types.Block) error {
return nil
}
// InsertBlockWithoutSetHead executes the block, runs the necessary verification
// upon it and then persist the block and the associate state into the database.
// The key difference between the InsertChain is it won't do the canonical chain
@ -2795,3 +2788,7 @@ func (bc *BlockChain) SetBlockValidatorAndProcessorForTesting(v Validator, p Pro
func (bc *BlockChain) SetTrieFlushInterval(interval time.Duration) {
bc.flushInterval.Store(int64(interval))
}
func (bc *BlockChain) SubscribeChain2HeadEvent(ch chan<- Chain2HeadEvent) event.Subscription {
return bc.scope.Track(bc.chain2HeadFeed.Subscribe(ch))
}

View file

@ -17,6 +17,7 @@
package core
import (
"github.com/ethereum/go-ethereum/ethdb"
"math/big"
"github.com/ethereum/go-ethereum/common"

View file

@ -2583,8 +2583,7 @@ func TestTransactionIndices(t *testing.T) {
for _, l := range limit {
frdir := t.TempDir()
ancientDb, _ := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false)
// TODO marcello check following method (WriteAncientBlocks everywhere)
rawdb.WriteAncientBlocks(ancientDb, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), big.NewInt(0))
rawdb.WriteAncientBlocks(ancientDb, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), []types.Receipts{nil}, big.NewInt(0))
l := l
chain, err := NewBlockChain(ancientDb, nil, gspec, nil, ethash.NewFaker(), vm.Config{}, nil, &l, nil)
@ -2607,7 +2606,7 @@ func TestTransactionIndices(t *testing.T) {
ancientDb, _ := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), t.TempDir(), "", false)
defer ancientDb.Close()
rawdb.WriteAncientBlocks(ancientDb, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), big.NewInt(0))
rawdb.WriteAncientBlocks(ancientDb, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), []types.Receipts{nil}, big.NewInt(0))
limit = []uint64{0, 64 /* drop stale */, 32 /* shorten history */, 64 /* extend history */, 0 /* restore all */}
for _, l := range limit {
l := l
@ -4021,7 +4020,7 @@ func TestTxIndexer(t *testing.T) {
for _, c := range cases {
frdir := t.TempDir()
db, _ := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false)
rawdb.WriteAncientBlocks(db, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), big.NewInt(0))
rawdb.WriteAncientBlocks(db, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), []types.Receipts{nil}, big.NewInt(0))
// Index the initial blocks from ancient store
chain, _ := NewBlockChain(db, nil, gspec, nil, engine, vm.Config{}, nil, &c.limitA, nil)

View file

@ -100,7 +100,7 @@ func (b *BlockGen) addTx(bc *BlockChain, vmConfig vm.Config, tx *types.Transacti
b.SetCoinbase(common.Address{})
}
b.statedb.SetTxContext(tx.Hash(), len(b.txs))
receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vmConfig)
receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vmConfig, nil)
if err != nil {
panic(err)
}
@ -130,7 +130,7 @@ func (b *BlockGen) AddTx(tx *types.Transaction) {
// the block in chain will be returned.
func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
b.addTx(bc, vm.Config{}, tx)
b.statedb.Prepare(tx.Hash(), len(b.txs))
b.statedb.SetTxContext(tx.Hash(), len(b.txs))
receipt, err := ApplyTransaction(b.config, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{}, nil)
if err != nil {
panic(err)

View file

@ -61,7 +61,7 @@ type Floater interface {
Float64() float64
}
func NewForkChoice(chainReader ChainReader, preserve func(header *types.Header) bool) *ForkChoice {
func NewForkChoice(chainReader ChainReader, preserve func(header *types.Header) bool, validator ethereum.ChainValidator) *ForkChoice {
// Seed a fast but crypto originating random generator
r := crand.NewRand()
return &ForkChoice{

View file

@ -19,7 +19,6 @@ package forkid
import (
"bytes"
"math"
"math/big"
"testing"
"github.com/ethereum/go-ethereum/common"
@ -30,8 +29,6 @@ import (
// TestCreation tests that different genesis and fork rule combinations result in
// the correct fork ID.
func TestCreation(t *testing.T) {
mergeConfig := *params.MainnetChainConfig
mergeConfig.MergeForkBlock = big.NewInt(15000000)
type testcase struct {
head uint64
time uint64
@ -77,30 +74,6 @@ func TestCreation(t *testing.T) {
{30000000, 2000000000, ID{Hash: checksumToBytes(0xdce96c2d), Next: 0}}, // Future Shanghai block
},
},
// Rinkeby test cases
{
params.RinkebyChainConfig,
params.RinkebyGenesisHash,
[]testcase{
{0, 0, ID{Hash: checksumToBytes(0x3b8e0691), Next: 1}}, // Unsynced, last Frontier block
{1, 0, ID{Hash: checksumToBytes(0x60949295), Next: 2}}, // First and last Homestead block
{2, 0, ID{Hash: checksumToBytes(0x8bde40dd), Next: 3}}, // First and last Tangerine block
{3, 0, ID{Hash: checksumToBytes(0xcb3a64bb), Next: 1035301}}, // First Spurious block
{1035300, 0, ID{Hash: checksumToBytes(0xcb3a64bb), Next: 1035301}}, // Last Spurious block
{1035301, 0, ID{Hash: checksumToBytes(0x8d748b57), Next: 3660663}}, // First Byzantium block
{3660662, 0, ID{Hash: checksumToBytes(0x8d748b57), Next: 3660663}}, // Last Byzantium block
{3660663, 0, ID{Hash: checksumToBytes(0xe49cab14), Next: 4321234}}, // First Constantinople block
{4321233, 0, ID{Hash: checksumToBytes(0xe49cab14), Next: 4321234}}, // Last Constantinople block
{4321234, 0, ID{Hash: checksumToBytes(0xafec6b27), Next: 5435345}}, // First Petersburg block
{5435344, 0, ID{Hash: checksumToBytes(0xafec6b27), Next: 5435345}}, // Last Petersburg block
{5435345, 0, ID{Hash: checksumToBytes(0xcbdb8838), Next: 8290928}}, // First Istanbul block
{8290927, 0, ID{Hash: checksumToBytes(0xcbdb8838), Next: 8290928}}, // Last Istanbul block
{8290928, 0, ID{Hash: checksumToBytes(0x6910c8bd), Next: 8897988}}, // First Berlin block
{8897987, 0, ID{Hash: checksumToBytes(0x6910c8bd), Next: 8897988}}, // Last Berlin block
{8897988, 0, ID{Hash: checksumToBytes(0x8E29F2F3), Next: 0}}, // First London block
{10000000, 0, ID{Hash: checksumToBytes(0x8E29F2F3), Next: 0}}, // Future London block
},
},
// Goerli test cases
{
params.GoerliChainConfig,
@ -130,38 +103,6 @@ func TestCreation(t *testing.T) {
{1735372, 1677557088, ID{Hash: checksumToBytes(0xf7f9bc08), Next: 0}}, // First Shanghai block
},
},
// Merge test cases
{
&mergeConfig,
params.MainnetGenesisHash,
[]testcase{
{0, 0, ID{Hash: checksumToBytes(0xfc64ec04), Next: 1150000}}, // Unsynced
{1149999, 0, ID{Hash: checksumToBytes(0xfc64ec04), Next: 1150000}}, // Last Frontier block
{1150000, 0, ID{Hash: checksumToBytes(0x97c2c34c), Next: 1920000}}, // First Homestead block
{1919999, 0, ID{Hash: checksumToBytes(0x97c2c34c), Next: 1920000}}, // Last Homestead block
{1920000, 0, ID{Hash: checksumToBytes(0x91d1f948), Next: 2463000}}, // First DAO block
{2462999, 0, ID{Hash: checksumToBytes(0x91d1f948), Next: 2463000}}, // Last DAO block
{2463000, 0, ID{Hash: checksumToBytes(0x7a64da13), Next: 2675000}}, // First Tangerine block
{2674999, 0, ID{Hash: checksumToBytes(0x7a64da13), Next: 2675000}}, // Last Tangerine block
{2675000, 0, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}}, // First Spurious block
{4369999, 0, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}}, // Last Spurious block
{4370000, 0, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}}, // First Byzantium block
{7279999, 0, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}}, // Last Byzantium block
{7280000, 0, ID{Hash: checksumToBytes(0x668db0af), Next: 9069000}}, // First and last Constantinople, first Petersburg block
{9068999, 0, ID{Hash: checksumToBytes(0x668db0af), Next: 9069000}}, // Last Petersburg block
{9069000, 0, ID{Hash: checksumToBytes(0x879d6e30), Next: 9200000}}, // First Istanbul and first Muir Glacier block
{9199999, 0, ID{Hash: checksumToBytes(0x879d6e30), Next: 9200000}}, // Last Istanbul and first Muir Glacier block
{9200000, 0, ID{Hash: checksumToBytes(0xe029e991), Next: 12244000}}, // First Muir Glacier block
{12243999, 0, ID{Hash: checksumToBytes(0xe029e991), Next: 12244000}}, // Last Muir Glacier block
{12244000, 0, ID{Hash: checksumToBytes(0x0eb440f6), Next: 12965000}}, // First Berlin block
{12964999, 0, ID{Hash: checksumToBytes(0x0eb440f6), Next: 12965000}}, // Last Berlin block
{12965000, 0, ID{Hash: checksumToBytes(0xb715077d), Next: 13773000}}, // First London block
{13772999, 0, ID{Hash: checksumToBytes(0xb715077d), Next: 13773000}}, // Last London block
{13773000, 0, ID{Hash: checksumToBytes(0x20c327fc), Next: 15000000}}, // First Arrow Glacier block
{15000000, 0, ID{Hash: checksumToBytes(0xe3abe201), Next: 0}}, // First Merge Start block
{20000000, 0, ID{Hash: checksumToBytes(0xe3abe201), Next: 0}}, // Future Merge Start block
},
},
}
for i, tt := range tests {
for j, ttt := range tt.cases {

View file

@ -378,7 +378,7 @@ func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int)
//
// The returned 'write status' says if the inserted headers are part of the canonical chain
// or a side chain.
func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, start time.Time) (WriteStatus, error) {
func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, start time.Time, forker *ForkChoice) (WriteStatus, error) {
if hc.procInterrupt() {
return 0, errors.New("aborted")
}

View file

@ -15,9 +15,6 @@ var (
// bor receipt key
borReceiptKey = types.BorReceiptKey
// bor derived tx hash
getDerivedBorTxHash = types.GetDerivedBorTxHash
// borTxLookupPrefix + hash -> transaction/receipt lookup metadata
borTxLookupPrefix = []byte(borTxLookupPrefixStr)
)
@ -37,7 +34,7 @@ func borTxLookupKey(hash common.Hash) []byte {
func ReadBorReceiptRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
var data []byte
err := db.ReadAncients(func(reader ethdb.AncientReader) error {
err := db.ReadAncients(func(reader ethdb.AncientReaderOp) error {
// Check if the data is in ancients
if isCanon(reader, number, hash) {
data, _ = reader.Ancient(freezerBorReceiptTable, number)

View file

@ -268,8 +268,8 @@ func (p *Pruner) Prune(root common.Hash) error {
// is the presence of root can indicate the presence of the
// entire trie.
if !rawdb.HasLegacyTrieNode(p.db, root) {
// The special case is for clique based networks(rinkeby, goerli
// and some other private networks), it's possible that two
// The special case is for clique based networks(goerli and
// some other private networks), it's possible that two
// consecutive blocks will have same root. In this case snapshot
// difflayer won't be created. So HEAD-127 may not paired with
// head-127 layer. Instead the paired layer is higher than the

View file

@ -404,7 +404,7 @@ func (st *StateTransition) TransitionDb(interruptCtx context.Context) (*Executio
amount := new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), effectiveTip)
if rules.isLondon {
if rules.IsLondon {
burntContractAddress := common.HexToAddress(st.evm.ChainConfig().Bor.CalculateBurntContract(st.evm.Context.BlockNumber.Uint64()))
burnAmount := new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.evm.Context.BaseFee)
st.state.AddBalance(burntContractAddress, burnAmount)

View file

@ -1812,7 +1812,7 @@ func testRepair(t *testing.T, tt *rewindTest, snapshots bool) {
chainConfig.LondonBlock = big.NewInt(0)
_, back, closeFn := miner.NewTestWorker(t, chainConfig, engine, db, 0, 0, 0, 0)
_, back, closeFn := miner.NewTestWorker(t, chainConfig, engine, db, 0, false, 0, 0)
defer closeFn()
genesis := back.BlockChain().Genesis()
@ -1879,7 +1879,6 @@ func testRepair(t *testing.T, tt *rewindTest, snapshots bool) {
// Pull the plug on the database, simulating a hard crash
db.Close()
chain.stopWithoutSaving()
// Start a new blockchain back up and see where the repair leads us
db, err = rawdb.Open(rawdb.OpenOptions{
@ -1893,7 +1892,21 @@ func testRepair(t *testing.T, tt *rewindTest, snapshots bool) {
defer db.Close()
newChain, err := core.NewBlockChain(db, nil, params.AllEthashProtocolChanges, engine, vm.Config{}, nil, nil, nil)
var (
gspec = &core.Genesis{
Config: params.TestChainConfig,
BaseFee: big.NewInt(params.InitialBaseFee),
}
config = &core.CacheConfig{
TrieCleanLimit: 256,
TrieDirtyLimit: 256,
TrieTimeLimit: 5 * time.Minute,
SnapshotLimit: 256,
SnapshotWait: true,
}
)
newChain, err := core.NewBlockChain(db, config, gspec, nil, engine, vm.Config{}, nil, nil, nil)
if err != nil {
t.Fatalf("Failed to recreate chain: %v", err)
}
@ -1958,12 +1971,12 @@ func TestIssue23496(t *testing.T) {
// Initialize a fresh chain
var (
gspec = &Genesis{
gspec = &core.Genesis{
Config: params.TestChainConfig,
BaseFee: big.NewInt(params.InitialBaseFee),
}
engine = ethash.NewFullFaker()
config = &CacheConfig{
config = &core.CacheConfig{
TrieCleanLimit: 256,
TrieDirtyLimit: 256,
TrieTimeLimit: 5 * time.Minute,
@ -1975,7 +1988,7 @@ func TestIssue23496(t *testing.T) {
if err != nil {
t.Fatalf("Failed to create chain: %v", err)
}
_, blocks, _ := core.GenerateChainWithGenesis(gspec, engine, 4, func(i int, b *BlockGen) {
_, blocks, _ := core.GenerateChainWithGenesis(gspec, engine, 4, func(i int, b *core.BlockGen) {
b.SetCoinbase(common.Address{0x02})
b.SetDifficulty(big.NewInt(1000000))
})
@ -1984,7 +1997,7 @@ func TestIssue23496(t *testing.T) {
if _, err := chain.InsertChain(blocks[:1]); err != nil {
t.Fatalf("Failed to import canonical chain start: %v", err)
}
err = chain.StateCache().TrieDB().Commit(blocks[0].Root(), true, nil)
err = chain.StateCache().TrieDB().Commit(blocks[0].Root(), true)
if err != nil {
t.Fatal("on trieDB.Commit", err)
}
@ -1992,7 +2005,7 @@ func TestIssue23496(t *testing.T) {
if _, err := chain.InsertChain(blocks[1:2]); err != nil {
t.Fatalf("Failed to import canonical chain start: %v", err)
}
if err := chain.snaps.Cap(blocks[1].Root(), 0); err != nil {
if err := chain.Snaps().Cap(blocks[1].Root(), 0); err != nil {
t.Fatalf("Failed to flatten snapshots: %v", err)
}
@ -2000,20 +2013,19 @@ func TestIssue23496(t *testing.T) {
if _, err := chain.InsertChain(blocks[2:3]); err != nil {
t.Fatalf("Failed to import canonical chain start: %v", err)
}
chain.stateCache.TrieDB().Commit(blocks[2].Root(), false)
chain.StateCache().TrieDB().Commit(blocks[2].Root(), false)
// Insert the remaining blocks
if _, err := chain.InsertChain(blocks[3:]); err != nil {
t.Fatalf("Failed to import canonical chain tail: %v", err)
}
err = chain.StateCache().TrieDB().Commit(blocks[2].Root(), true, nil)
err = chain.StateCache().TrieDB().Commit(blocks[2].Root(), true)
if err != nil {
t.Fatal("on trieDB.Commit", err)
}
// Pull the plug on the database, simulating a hard crash
db.Close()
chain.stopWithoutSaving()
// Start a new blockchain back up and see where the repair leads us
db, err = rawdb.Open(rawdb.OpenOptions{
@ -2025,7 +2037,7 @@ func TestIssue23496(t *testing.T) {
}
defer db.Close()
chain, err = NewBlockChain(db, nil, gspec, nil, engine, vm.Config{}, nil, nil)
chain, err = core.NewBlockChain(db, nil, gspec, nil, engine, vm.Config{}, nil, nil, nil)
if err != nil {
t.Fatalf("Failed to recreate chain: %v", err)
}

View file

@ -2000,7 +2000,7 @@ func testSetHead(t *testing.T, tt *rewindTest, snapshots bool) {
t.Fatalf("Failed to import side chain: %v", err)
}
}
canonblocks, _ := core.GenerateChain(gspec.Config, gspec.ToBlock(), engine, rawdb.NewMemoryDatabase(), tt.canonicalBlocks, func(i int, b *BlockGen) {
canonblocks, _ := core.GenerateChain(gspec.Config, gspec.ToBlock(), engine, rawdb.NewMemoryDatabase(), tt.canonicalBlocks, func(i int, b *core.BlockGen) {
b.SetCoinbase(common.Address{0x02})
b.SetDifficulty(big.NewInt(1000000))
})
@ -2008,7 +2008,7 @@ func testSetHead(t *testing.T, tt *rewindTest, snapshots bool) {
t.Fatalf("Failed to import canonical chain start: %v", err)
}
if tt.commitBlock > 0 {
err = chain.StateCache().TrieDB().Commit(canonblocks[tt.commitBlock-1].Root(), true, nil)
err = chain.StateCache().TrieDB().Commit(canonblocks[tt.commitBlock-1].Root(), true)
if err != nil {
t.Fatal("on trieDB.Commit", err)
}

View file

@ -55,7 +55,7 @@ type snapshotTestBasic struct {
db ethdb.Database
genDb ethdb.Database
engine consensus.Engine
gspec *Genesis
gspec *core.Genesis
}
func (basic *snapshotTestBasic) prepare(t *testing.T) (*core.BlockChain, []*types.Block) {
@ -105,7 +105,7 @@ func (basic *snapshotTestBasic) prepare(t *testing.T) (*core.BlockChain, []*type
startPoint = point
if basic.commitBlock > 0 && basic.commitBlock == point {
err = chain.StateCache().TrieDB().Commit(blocks[point-1].Root(), true, nil)
err = chain.StateCache().TrieDB().Commit(blocks[point-1].Root(), true)
if err != nil {
t.Fatal("on trieDB.Commit", err)
}
@ -267,7 +267,6 @@ func (snaptest *crashSnapshotTest) test(t *testing.T) {
// Pull the plug on the database, simulating a hard crash
db := chain.DB()
db.Close()
chain.stopWithoutSaving()
// Start a new blockchain back up and see where the repair leads us
newdb, err := rawdb.Open(rawdb.OpenOptions{
@ -414,14 +413,11 @@ func (snaptest *wipeCrashSnapshotTest) test(t *testing.T) {
SnapshotLimit: 256,
SnapshotWait: false, // Don't wait rebuild
}
tmp, err := core.NewBlockChain(snaptest.db, config, snaptest.gspec, nil, snaptest.engine, vm.Config{}, nil, nil, nil)
_, err = core.NewBlockChain(snaptest.db, config, snaptest.gspec, nil, snaptest.engine, vm.Config{}, nil, nil, nil)
if err != nil {
t.Fatalf("Failed to recreate chain: %v", err)
}
// Simulate the blockchain crash.
tmp.stopWithoutSaving()
newchain, err = core.NewBlockChain(snaptest.db, nil, snaptest.gspec, nil, snaptest.engine, vm.Config{}, nil, nil, nil)
if err != nil {
t.Fatalf("Failed to recreate chain: %v", err)

View file

@ -436,7 +436,6 @@ func newList(strict bool) *list {
return &list{
strict: strict,
txs: newSortedMap(),
costcap: new(big.Int),
totalcost: new(big.Int),
}
}

View file

@ -17,6 +17,7 @@
package txpool
import (
"github.com/holiman/uint256"
"math/big"
"math/rand"
"testing"
@ -68,7 +69,7 @@ func BenchmarkListAdd(b *testing.B) {
list := newList(true)
for _, v := range rand.Perm(len(txs)) {
list.Add(txs[v], DefaultConfig.PriceBump)
list.Filter(priceLimit, DefaultConfig.PriceBump)
list.Filter(uint256.NewInt(priceLimit.Uint64()), DefaultConfig.PriceBump)
}
}
}

View file

@ -33,7 +33,6 @@ import (
"go.opentelemetry.io/otel/trace"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/prque"
"github.com/ethereum/go-ethereum/common/tracing"
"github.com/ethereum/go-ethereum/consensus/misc"
"github.com/ethereum/go-ethereum/core"
@ -823,7 +822,7 @@ func (pool *TxPool) validateTxBasics(tx *types.Transaction, local bool) error {
}
}
// Ensure the transaction has more gas than the basic tx fee.
intrGas, err := IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil, true, pool.istanbul)
intrGas, err := core.IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil, true, pool.istanbul.Load(), pool.shanghai.Load())
if err != nil {
return err
}
@ -835,6 +834,38 @@ func (pool *TxPool) validateTxBasics(tx *types.Transaction, local bool) error {
return nil
}
// validateTx checks whether a transaction is valid according to the consensus
// rules and adheres to some heuristic limits of the local node (price and size).
func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error {
// Signature has been checked already, this cannot error.
from, _ := types.Sender(pool.signer, tx)
// Ensure the transaction adheres to nonce ordering
if pool.currentState.GetNonce(from) > tx.Nonce() {
return core.ErrNonceTooLow
}
// Transactor should have enough funds to cover the costs
// cost == V + GP * GL
balance := pool.currentState.GetBalance(from)
if balance.Cmp(tx.Cost()) < 0 {
return core.ErrInsufficientFunds
}
// Verify that replacing transactions will not result in overdraft
list := pool.pending[from]
if list != nil { // Sender already has pending txs
sum := new(big.Int).Add(tx.Cost(), list.totalcost)
if repl := list.txs.Get(tx.Nonce()); repl != nil {
// Deduct the cost of a transaction replaced by this
sum.Sub(sum, repl.Cost())
}
if balance.Cmp(sum) < 0 {
log.Trace("Replacing transactions would overdraft", "sender", from, "balance", pool.currentState.GetBalance(from), "required", sum)
return ErrOverdraft
}
}
return nil
}
// add validates a transaction and inserts it into the non-executable queue for later
// pending promotion and execution. If the transaction is a replacement for an already
// pending or queued one, it overwrites the previous transaction if its price is higher.
@ -899,7 +930,7 @@ func (pool *TxPool) add(tx *types.Transaction, local bool) (replaced bool, err e
for _, dropTx := range drop {
dropSender, _ := types.Sender(pool.signer, dropTx)
if list := pool.pending[dropSender]; list != nil && list.Overlaps(dropTx) {
if list := pool.pending[dropSender]; list != nil && list.Contains(dropTx.Nonce()) {
replacesPending = true
break
}
@ -1850,7 +1881,7 @@ func (pool *TxPool) promoteExecutables(accounts []common.Address) []*types.Trans
// Drop all transactions that are too costly (low balance or out of gas)
balance.SetFromBig(pool.currentState.GetBalance(addr))
drops, _ = list.Filter(balance, pool.currentMaxGas)
drops, _ = list.Filter(balance, pool.currentMaxGas.Load())
dropsLen = len(drops)
for _, tx := range drops {
@ -1928,7 +1959,7 @@ func (pool *TxPool) truncatePending() {
}
// Assemble a spam order to penalize large transactors first
spammers := prque.New[int64, common.Address](nil)
spammers := make([]pair, 0, 8)
count := 0
var ok bool
@ -1980,7 +2011,7 @@ func (pool *TxPool) truncatePending() {
// todo: metrics: spammers, offenders, total loops
for len(spammers) != 0 && pending > pool.config.GlobalSlots {
// Retrieve the next offender if not local address
offender, _ := spammers.Pop()
offender, spammers = spammers[len(spammers)-1].address, spammers[:len(spammers)-1]
offenders = append(offenders, offender)
// Equalize balances until all the same or below threshold
@ -2178,7 +2209,7 @@ func (pool *TxPool) demoteUnexecutables() {
// Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later
balance.SetFromBig(pool.currentState.GetBalance(addr))
drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas.Load())
drops, invalids := list.Filter(balance, pool.currentMaxGas.Load())
dropsLen = len(drops)
invalidsLen = len(invalids)
@ -2219,9 +2250,7 @@ func (pool *TxPool) demoteUnexecutables() {
pool.enqueueTx(hash, tx, false, false)
}
pendingGauge.Dec(int64(len(gapped)))
// This might happen in a reorg, so log it to the metering
blockReorgInvalidatedTx.Mark(int64(gappedLen))
pendingGauge.Dec(int64(gappedLen))
}
// Delete the entire pending entry if it became empty.

View file

@ -111,10 +111,11 @@ type Ethereum struct {
// New creates a new Ethereum object (including the
// initialisation of the common Ethereum object)
// TODO fixme marcello c'é qcls che non va qua (CreateConsensusEngine chiamata due volte)
func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
// Ensure configuration values are compatible and sane
if config.SyncMode == downloader.LightSync {
return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum")
return nil, errors.New("can't run ethereum.Ethereum in light sync mode, use les.LightEthereum")
}
if !config.SyncMode.IsValid() {
return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode)
@ -135,7 +136,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
log.Info("Allocated trie memory caches", "clean", common.StorageSize(config.TrieCleanCache)*1024*1024, "dirty", common.StorageSize(config.TrieDirtyCache)*1024*1024)
// Assemble the Ethereum object
chainDb, err := stack.OpenDatabaseWithFreezer("chaindata", config.DatabaseCache, config.DatabaseHandles, config.DatabaseFreezer, "eth/db/chaindata/", false)
chainDb, err := stack.OpenDatabaseWithFreezer("chaindata", config.DatabaseCache, config.DatabaseHandles, config.DatabaseFreezer, "ethereum/db/chaindata/", false)
if err != nil {
return nil, err
}
@ -149,16 +150,15 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
if err != nil {
return nil, err
}
engine := ethconfig.CreateConsensusEngine(stack, &ethashConfig, cliqueConfig, config.Miner.Notify, config.Miner.Noverify, chainDb)
eth := &Ethereum{
// START: Bor changes
ethereum := &Ethereum{
config: config,
merger: consensus.NewMerger(chainDb),
chainDb: chainDb,
eventMux: stack.EventMux(),
accountManager: stack.AccountManager(),
authorized: false,
engine: engine,
closeBloomHandler: make(chan struct{}),
networkID: config.NetworkId,
gasPrice: config.Miner.GasPrice,
@ -170,9 +170,8 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
shutdownTracker: shutdowncheck.NewShutdownTracker(chainDb),
}
// START: Bor changes
eth.APIBackend = &EthAPIBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, eth, nil}
if eth.APIBackend.allowUnprotectedTxs {
ethereum.APIBackend = &EthAPIBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, ethereum, nil}
if ethereum.APIBackend.allowUnprotectedTxs {
log.Debug(" ###########", "Unprotected transactions allowed")
config.TxPool.AllowUnprotectedTxs = true
@ -181,11 +180,12 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
if gpoParams.Default == nil {
gpoParams.Default = config.Miner.GasPrice
}
eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams)
ethereum.APIBackend.gpo = gasprice.NewOracle(ethereum.APIBackend, gpoParams)
// create eth api and set engine
ethAPI := ethapi.NewPublicBlockChainAPI(eth.APIBackend)
eth.engine = ethconfig.CreateConsensusEngine(stack, chainConfig, config, config.Miner.Notify, config.Miner.Noverify, chainDb, ethAPI)
blockChainAPI := ethapi.NewBlockChainAPI(ethereum.APIBackend)
// TODO marcello fix configs (using nil atm)
engine := ethconfig.CreateConsensusEngine(stack, nil, nil, &ethashConfig, cliqueConfig, config.Miner.Notify, config.Miner.Noverify, chainDb, nil)
ethereum.engine = engine
// END: Bor changes
bcVersion := rawdb.ReadDatabaseVersion(chainDb)
@ -230,83 +230,73 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
checker := whitelist.NewService(10)
eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, config.Genesis, &overrides, eth.engine, vmConfig, eth.shouldPreserve, &config.TxLookupLimit, checker)
ethereum.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, config.Genesis, &overrides, ethereum.engine, vmConfig, ethereum.shouldPreserve, &config.TxLookupLimit, checker)
if err != nil {
return nil, err
}
eth.engine.VerifyHeader(eth.blockchain, eth.blockchain.CurrentHeader(), true) // TODO think on it
ethereum.engine.VerifyHeader(ethereum.blockchain, ethereum.blockchain.CurrentHeader(), true) // TODO think on it
// BOR changes
eth.APIBackend.gpo.ProcessCache()
ethereum.APIBackend.gpo.ProcessCache()
// BOR changes
eth.bloomIndexer.Start(eth.blockchain)
ethereum.bloomIndexer.Start(ethereum.blockchain)
if config.TxPool.Journal != "" {
config.TxPool.Journal = stack.ResolvePath(config.TxPool.Journal)
}
eth.txPool = txpool.NewTxPool(config.TxPool, eth.blockchain.Config(), eth.blockchain)
ethereum.txPool = txpool.NewTxPool(config.TxPool, ethereum.blockchain.Config(), ethereum.blockchain)
// Permit the downloader to use the trie cache allowance during fast sync
cacheLimit := cacheConfig.TrieCleanLimit + cacheConfig.TrieDirtyLimit + cacheConfig.SnapshotLimit
checkpoint := config.Checkpoint
if checkpoint == nil {
checkpoint = params.TrustedCheckpoints[eth.blockchain.Genesis().Hash()]
checkpoint = params.TrustedCheckpoints[ethereum.blockchain.Genesis().Hash()]
}
if eth.handler, err = newHandler(&handlerConfig{
if ethereum.handler, err = newHandler(&handlerConfig{
Database: chainDb,
Chain: eth.blockchain,
TxPool: eth.txPool,
Merger: eth.merger,
Chain: ethereum.blockchain,
TxPool: ethereum.txPool,
Merger: ethereum.merger,
Network: config.NetworkId,
Sync: config.SyncMode,
BloomCache: uint64(cacheLimit),
EventMux: eth.eventMux,
EventMux: ethereum.eventMux,
Checkpoint: checkpoint,
RequiredBlocks: config.RequiredBlocks,
EthAPI: ethAPI,
EthAPI: blockChainAPI,
checker: checker,
txArrivalWait: eth.p2pServer.TxArrivalWait,
txArrivalWait: ethereum.p2pServer.TxArrivalWait,
}); err != nil {
return nil, err
}
eth.miner = miner.New(eth, &config.Miner, eth.blockchain.Config(), eth.EventMux(), eth.engine, eth.isLocalBlock)
eth.miner.SetExtra(makeExtraData(config.Miner.ExtraData))
eth.APIBackend = &EthAPIBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, eth, nil}
if eth.APIBackend.allowUnprotectedTxs {
log.Info("Unprotected transactions allowed")
}
gpoParams := config.GPO
if gpoParams.Default == nil {
gpoParams.Default = config.Miner.GasPrice
}
eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams)
ethereum.miner = miner.New(ethereum, &config.Miner, ethereum.blockchain.Config(), ethereum.EventMux(), ethereum.engine, ethereum.isLocalBlock)
ethereum.miner.SetExtra(makeExtraData(config.Miner.ExtraData))
// Setup DNS discovery iterators.
dnsclient := dnsdisc.NewClient(dnsdisc.Config{})
eth.ethDialCandidates, err = dnsclient.NewIterator(eth.config.EthDiscoveryURLs...)
ethereum.ethDialCandidates, err = dnsclient.NewIterator(ethereum.config.EthDiscoveryURLs...)
if err != nil {
return nil, err
}
eth.snapDialCandidates, err = dnsclient.NewIterator(eth.config.SnapDiscoveryURLs...)
ethereum.snapDialCandidates, err = dnsclient.NewIterator(ethereum.config.SnapDiscoveryURLs...)
if err != nil {
return nil, err
}
// Start the RPC service
eth.netRPCService = ethapi.NewNetAPI(eth.p2pServer, config.NetworkId)
ethereum.netRPCService = ethapi.NewNetAPI(ethereum.p2pServer, config.NetworkId)
// Register the backend on the node
stack.RegisterAPIs(eth.APIs())
stack.RegisterProtocols(eth.Protocols())
stack.RegisterLifecycle(eth)
stack.RegisterAPIs(ethereum.APIs())
stack.RegisterProtocols(ethereum.Protocols())
stack.RegisterLifecycle(ethereum)
// Successful startup; push a marker and check previous unclean shutdowns.
eth.shutdownTracker.MarkStartup()
ethereum.shutdownTracker.MarkStartup()
return eth, nil
return ethereum, nil
}
func makeExtraData(extra []byte) []byte {
@ -335,8 +325,9 @@ func (s *Ethereum) APIs() []rpc.API {
apis = append(apis, s.engine.APIs(s.BlockChain())...)
// BOR change starts
filterSystem := filters.NewFilterSystem(s.APIBackend, filters.Config{})
// set genesis to public filter api
publicFilterAPI := filters.NewFilterAPI(s.APIBackend, false, 5*time.Minute, s.config.BorLogs)
publicFilterAPI := filters.NewFilterAPI(filterSystem, false, s.config.BorLogs)
// avoiding constructor changed by introducing new method to set genesis
publicFilterAPI.SetChainConfig(s.blockchain.Config())
// BOR change ends

View file

@ -18,6 +18,7 @@
package ethconfig
import (
"github.com/ethereum/go-ethereum/internal/ethapi"
"os"
"os/user"
"path/filepath"
@ -243,11 +244,10 @@ type Config struct {
// Develop Fake Author mode to produce blocks without authorisation
DevFakeAuthor bool `hcl:"devfakeauthor,optional" toml:"devfakeauthor,optional"`
}
// CreateConsensusEngine creates a consensus engine for the given chain configuration.
func CreateConsensusEngine(stack *node.Node, ethashConfig *ethash.Config, cliqueConfig *params.CliqueConfig, notify []string, noverify bool, db ethdb.Database) consensus.Engine {
func CreateConsensusEngine(stack *node.Node, chainConfig *params.ChainConfig, ethConfig *Config, ethashConfig *ethash.Config, cliqueConfig *params.CliqueConfig, notify []string, noverify bool, db ethdb.Database, blockchainAPI *ethapi.BlockChainAPI) consensus.Engine {
// If proof-of-authority is requested, set it up
var engine consensus.Engine
if cliqueConfig != nil {
@ -257,8 +257,9 @@ func CreateConsensusEngine(stack *node.Node, ethashConfig *ethash.Config, clique
// If Matic bor consensus is requested, set it up
// In order to pass the ethereum transaction tests, we need to set the burn contract which is in the bor config
// Then, bor != nil will also be enabled for ethash and clique. Only enable Bor for real if there is a validator contract present.
// TODO marcello FIXME based on proper ethConfig for Bor (ideally ethashConfig) and blockchainAPI
if ethashConfig.Bor != nil && chainConfig.Bor.ValidatorContract != "" {
if chainConfig.Bor != nil && chainConfig.Bor.ValidatorContract != "" {
genesisContractsClient := contract.NewGenesisContractsClient(chainConfig, chainConfig.Bor.ValidatorContract, chainConfig.Bor.StateReceiverContract, blockchainAPI)
spanner := span.NewChainSpanner(blockchainAPI, contract.ValidatorSet(), chainConfig, common.HexToAddress(chainConfig.Bor.ValidatorContract))

View file

@ -342,7 +342,7 @@ func (api *FilterAPI) GetLogs(ctx context.Context, crit FilterCriteria) ([]*type
var borLogsFilter *BorBlockLogsFilter
if crit.BlockHash != nil {
// Block filter requested, construct a single-shot filter
filter = NewBlockFilter(api.sys.backend, *crit.BlockHash, crit.Addresses, crit.Topics)
filter = api.sys.NewBlockFilter(*crit.BlockHash, crit.Addresses, crit.Topics)
// Block bor filter
if api.borLogs {
borLogsFilter = NewBorBlockLogsFilter(api.sys.backend, borConfig, *crit.BlockHash, crit.Addresses, crit.Topics)

View file

@ -12,11 +12,11 @@ import (
)
// SetChainConfig sets chain config
func (api *PublicFilterAPI) SetChainConfig(chainConfig *params.ChainConfig) {
func (api *FilterAPI) SetChainConfig(chainConfig *params.ChainConfig) {
api.chainConfig = chainConfig
}
func (api *PublicFilterAPI) GetBorBlockLogs(ctx context.Context, crit FilterCriteria) ([]*types.Log, error) {
func (api *FilterAPI) GetBorBlockLogs(ctx context.Context, crit FilterCriteria) ([]*types.Log, error) {
if api.chainConfig == nil {
return nil, errors.New("no chain config found. Proper PublicFilterAPI initialization required")
}
@ -27,7 +27,7 @@ func (api *PublicFilterAPI) GetBorBlockLogs(ctx context.Context, crit FilterCrit
var filter *BorBlockLogsFilter
if crit.BlockHash != nil {
// Block filter requested, construct a single-shot filter
filter = NewBorBlockLogsFilter(api.backend, borConfig, *crit.BlockHash, crit.Addresses, crit.Topics)
filter = NewBorBlockLogsFilter(api.sys.backend, borConfig, *crit.BlockHash, crit.Addresses, crit.Topics)
} else {
// Convert the RPC block numbers into internal representations
begin := rpc.LatestBlockNumber.Int64()
@ -39,7 +39,7 @@ func (api *PublicFilterAPI) GetBorBlockLogs(ctx context.Context, crit FilterCrit
end = crit.ToBlock.Int64()
}
// Construct the range filter
filter = NewBorBlockLogsRangeFilter(api.backend, borConfig, begin, end, crit.Addresses, crit.Topics)
filter = NewBorBlockLogsRangeFilter(api.sys.backend, borConfig, begin, end, crit.Addresses, crit.Topics)
}
// Run the filter and return all the logs
@ -51,7 +51,7 @@ func (api *PublicFilterAPI) GetBorBlockLogs(ctx context.Context, crit FilterCrit
}
// NewDeposits send a notification each time a new deposit received from bridge.
func (api *PublicFilterAPI) NewDeposits(ctx context.Context, crit ethereum.StateSyncFilter) (*rpc.Subscription, error) {
func (api *FilterAPI) NewDeposits(ctx context.Context, crit ethereum.StateSyncFilter) (*rpc.Subscription, error) {
notifier, supported := rpc.NotifierFromContext(ctx)
if !supported {
return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported

View file

@ -73,6 +73,7 @@ type Backend interface {
SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription
SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription
SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription
SubscribeStateSyncEvent(ch chan<- core.StateSyncEvent) event.Subscription
BloomStatus() (uint64, uint64)
ServiceFilter(ctx context.Context, session *bloombits.MatcherSession)

103
go.mod
View file

@ -4,8 +4,7 @@ go 1.19
require (
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v0.3.0
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v0.3.0
github.com/BurntSushi/toml v1.1.0
github.com/BurntSushi/toml v1.2.0
github.com/JekaMas/crand v1.0.1
github.com/JekaMas/go-grpc-net-conn v0.0.0-20220708155319-6aff21f2d13d
github.com/JekaMas/workerpool v1.1.5
@ -28,7 +27,7 @@ require (
github.com/fjl/gencodec v0.0.0-20220412091415-8bb9e558978c
github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5
github.com/fsnotify/fsnotify v1.6.0
github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff
github.com/gballet/go-libpcsclite v0.0.0-20191108122812-4678299bea08
github.com/gballet/go-verkle v0.0.0-20220902153445-097bd83b7732
github.com/go-stack/stack v1.8.1
github.com/gofrs/flock v0.8.1
@ -44,47 +43,32 @@ require (
github.com/hashicorp/go-bexpr v0.1.10
github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d
github.com/hashicorp/hcl/v2 v2.10.1
github.com/holiman/big v0.0.0-20221017200358-a027dc42d04e
github.com/holiman/bloomfilter/v2 v2.0.3
github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c
github.com/huin/goupnp v1.0.3
github.com/holiman/uint256 v1.2.0
github.com/huin/goupnp v1.0.3
github.com/imdario/mergo v0.3.11
github.com/influxdata/influxdb v1.8.3
github.com/influxdata/influxdb-client-go/v2 v2.4.0
github.com/influxdata/influxdb1-client v0.0.0-20220302092344-a9ab5670611c
github.com/jackpal/go-nat-pmp v1.0.2
github.com/jackpal/go-nat-pmp v1.0.2
github.com/jedisct1/go-minisign v0.0.0-20190909160543-45766022959e
github.com/julienschmidt/httprouter v1.3.0
github.com/karalabe/usb v0.0.2
github.com/kylelemons/godebug v1.1.0
github.com/mattn/go-colorable v0.1.13
github.com/mattn/go-isatty v0.0.16
github.com/naoina/toml v0.1.2-0.20170918210437-9fafd6967416
github.com/julienschmidt/httprouter v1.3.0
github.com/karalabe/usb v0.0.2
github.com/maticnetwork/crand v1.0.2
github.com/maticnetwork/heimdall v0.3.1-0.20230105132832-d0063f71e3f0
github.com/maticnetwork/polyproto v0.0.2
github.com/mattn/go-colorable v0.1.8
github.com/mattn/go-isatty v0.0.12
github.com/mattn/go-colorable v0.1.13
github.com/mattn/go-isatty v0.0.16
github.com/mitchellh/cli v1.1.2
github.com/mitchellh/go-homedir v1.1.0
github.com/olekukonko/tablewriter v0.0.5
github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7
github.com/peterh/liner v1.2.0
github.com/prometheus/tsdb v0.10.0
github.com/rjeczalik/notify v0.9.2
github.com/rs/cors v1.7.0
github.com/ryanuber/columnize v2.1.2+incompatible
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible
github.com/status-im/keycard-go v0.2.0
github.com/stretchr/testify v1.8.0
github.com/supranational/blst v0.3.8-0.20220526154634-513d2456b344
github.com/status-im/keycard-go v0.0.0-20211109104530-b0e0482ba91d
github.com/stretchr/testify v1.8.0
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7
github.com/tyler-smith/go-bip39 v1.1.0
github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa
@ -103,7 +87,7 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.21.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/internal v0.8.3 // indirect
github.com/DataDog/zstd v1.5.2 // indirect
github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6 // indirect
github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.0.2 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.0.2 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.1.1 // indirect
@ -122,7 +106,7 @@ require (
github.com/dlclark/regexp2 v1.7.0 // indirect
github.com/garslo/gogen v0.0.0-20170306192744-1d203ffc1f61 // indirect
github.com/getsentry/sentry-go v0.18.0 // indirect
github.com/go-ole/go-ole v1.2.1 // indirect
github.com/go-ole/go-ole v1.2.5 // indirect
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/influxdata/line-protocol v0.0.0-20210311194329-9aa0e372d097 // indirect
@ -134,8 +118,7 @@ require (
github.com/mitchellh/mapstructure v1.4.1 // indirect
github.com/mitchellh/pointerstructure v1.2.0 // indirect
github.com/mmcloughlin/addchain v0.4.0 // indirect
github.com/naoina/go-stringutil v0.1.0 // indirect
github.com/opentracing/opentracing-go v1.1.0 // indirect
github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.14.0 // indirect
@ -147,89 +130,63 @@ require (
github.com/tklauser/go-sysconf v0.3.5 // indirect
github.com/tklauser/numcpus v0.2.2 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
golang.org/x/mod v0.9.0 // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
rsc.io/tmplfunc v0.0.3 // indirect
github.com/tyler-smith/go-bip39 v1.1.0
github.com/xsleonard/go-merkle v1.1.0
go.opentelemetry.io/otel v1.2.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.2.0
go.opentelemetry.io/otel/sdk v1.2.0
go.uber.org/goleak v1.1.12
golang.org/x/crypto v0.1.0
golang.org/x/sync v0.1.0
golang.org/x/sys v0.6.0
golang.org/x/text v0.8.0
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac
golang.org/x/tools v0.6.0
golang.org/x/mod v0.9.0 // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df // indirect
gonum.org/v1/gonum v0.11.0
google.golang.org/grpc v1.51.0
google.golang.org/protobuf v1.28.1
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce
gopkg.in/olebedev/go-duktape.v3 v3.0.0-20200619000410-60c24ae608a6
gopkg.in/urfave/cli.v1 v1.20.0
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gotest.tools v2.2.0+incompatible
pgregory.net/rapid v0.4.8
rsc.io/tmplfunc v0.0.3 // indirect
)
require (
github.com/btcsuite/btcd v0.22.0-beta // indirect
github.com/btcsuite/btcd v0.22.3 // indirect
github.com/gammazero/deque v0.2.1 // indirect
golang.org/x/lint v0.0.0-20200302205851-738671d3881b // indirect
golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c // indirect
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 // indirect
golang.org/x/oauth2 v0.3.0 // indirect
)
require (
cloud.google.com/go v0.65.0 // indirect
cloud.google.com/go/pubsub v1.3.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.21.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/internal v0.8.3 // indirect
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver v1.5.0 // indirect
github.com/Masterminds/sprig v2.22.0+incompatible // indirect
github.com/RichardKnop/logging v0.0.0-20190827224416-1a693bdd4fae // indirect
github.com/RichardKnop/machinery v1.7.4 // indirect
github.com/RichardKnop/redsync v1.2.0 // indirect
github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46 // indirect
github.com/agext/levenshtein v1.2.1 // indirect
github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 // indirect
github.com/aws/aws-sdk-go v1.29.15 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.0.2 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.0.2 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.1.1 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.1.1 // indirect
github.com/aws/smithy-go v1.1.0 // indirect
github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/speakeasy v0.1.0 // indirect
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b // indirect
github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce // indirect
github.com/cbergoon/merkletree v0.2.0 // indirect
github.com/cenkalti/backoff/v4 v4.1.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/cosmos/cosmos-sdk v0.37.4
github.com/cosmos/go-bip39 v0.0.0-20180618194314-52158e4697b8 // indirect
github.com/cosmos/ledger-cosmos-go v0.10.3 // indirect
github.com/cosmos/ledger-go v0.9.2 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
github.com/deepmap/oapi-codegen v1.8.2 // indirect
github.com/dlclark/regexp2 v1.4.1-0.20201116162257-a2a8dda75c91 // indirect
github.com/etcd-io/bbolt v1.3.3 // indirect
github.com/fsnotify/fsnotify v1.4.9 // indirect
github.com/go-kit/kit v0.10.0 // indirect
github.com/go-logfmt/logfmt v0.5.0 // indirect
github.com/go-ole/go-ole v1.2.5 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/go-redis/redis v6.15.7+incompatible // indirect
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect
github.com/gomodule/redigo v2.0.0+incompatible // indirect
github.com/google/go-cmp v0.5.8 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/googleapis/gax-go/v2 v2.0.5 // indirect
github.com/gorilla/mux v1.8.0 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
@ -238,38 +195,25 @@ require (
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/huandu/xstrings v1.3.2 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/influxdata/line-protocol v0.0.0-20210311194329-9aa0e372d097 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/jstemmer/go-junit-report v0.9.1 // indirect
github.com/kelseyhightower/envconfig v1.4.0 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/libp2p/go-buffer-pool v0.0.2 // indirect
github.com/magiconair/properties v1.8.1 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mitchellh/copystructure v1.0.0 // indirect
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect
github.com/mitchellh/mapstructure v1.4.1 // indirect
github.com/mitchellh/pointerstructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/pelletier/go-toml v1.9.5
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/posener/complete v1.1.1 // indirect
github.com/prometheus/client_golang v1.12.1 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/rakyll/statik v0.1.7 // indirect
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/spf13/afero v1.2.2 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/cobra v0.0.5 // indirect
github.com/spf13/cobra v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.4.0 // indirect
@ -281,8 +225,6 @@ require (
github.com/tendermint/iavl v0.12.4 // indirect
github.com/tendermint/tendermint v0.32.7
github.com/tendermint/tm-db v0.2.0 // indirect
github.com/tklauser/go-sysconf v0.3.5 // indirect
github.com/tklauser/numcpus v0.2.2 // indirect
github.com/xdg/scram v1.0.3 // indirect
github.com/xdg/stringprep v1.0.3 // indirect
github.com/zclconf/go-cty v1.8.0 // indirect
@ -292,16 +234,9 @@ require (
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.2.0 // indirect
go.opentelemetry.io/otel/trace v1.2.0
go.opentelemetry.io/proto/otlp v0.10.0 // indirect
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
golang.org/x/mod v0.8.0 // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/term v0.6.0 // indirect
golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect
google.golang.org/api v0.34.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20220725144611-272f38e5d71b // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
replace github.com/cosmos/cosmos-sdk => github.com/maticnetwork/cosmos-sdk v0.37.5-0.20220311095845-81690c6a53e7

610
go.sum

File diff suppressed because it is too large Load diff

View file

@ -1667,7 +1667,7 @@ func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrH
// Apply the transaction with the access list tracer
tracer := logger.NewAccessListTracer(accessList, args.from(), to, precompiles)
config := vm.Config{Tracer: tracer, Debug: true, NoBaseFee: true}
config := vm.Config{Tracer: tracer, NoBaseFee: true}
vmenv, _, err := b.GetEVM(ctx, msg, statedb, header, &config)
if err != nil {
return nil, 0, nil, err
@ -2330,7 +2330,6 @@ func (api *DebugAPI) GetTraceStack() string {
}
}
// NetAPI offers network related RPC methods
type NetAPI struct {
net *p2p.Server

View file

@ -8,7 +8,7 @@ import (
)
// GetRootHash returns root hash for given start and end block
func (s *PublicBlockChainAPI) GetRootHash(ctx context.Context, starBlockNr uint64, endBlockNr uint64) (string, error) {
func (s *BlockChainAPI) GetRootHash(ctx context.Context, starBlockNr uint64, endBlockNr uint64) (string, error) {
root, err := s.b.GetRootHash(ctx, starBlockNr, endBlockNr)
if err != nil {
return "", err
@ -16,7 +16,7 @@ func (s *PublicBlockChainAPI) GetRootHash(ctx context.Context, starBlockNr uint6
return root, nil
}
func (s *PublicBlockChainAPI) GetBorBlockReceipt(ctx context.Context, hash common.Hash) (*types.Receipt, error) {
func (s *BlockChainAPI) GetBorBlockReceipt(ctx context.Context, hash common.Hash) (*types.Receipt, error) {
return s.b.GetBorBlockReceipt(ctx, hash)
}
@ -24,7 +24,7 @@ func (s *PublicBlockChainAPI) GetBorBlockReceipt(ctx context.Context, hash commo
// Bor transaction utils
//
func (s *PublicBlockChainAPI) appendRPCMarshalBorTransaction(ctx context.Context, block *types.Block, fields map[string]interface{}, fullTx bool) map[string]interface{} {
func (s *BlockChainAPI) appendRPCMarshalBorTransaction(ctx context.Context, block *types.Block, fields map[string]interface{}, fullTx bool) map[string]interface{} {
if block != nil {
txHash := types.GetDerivedBorTxHash(types.BorReceiptKey(block.Number().Uint64(), block.Hash()))
borTx, blockHash, blockNumber, txIndex, _ := s.b.GetBorBlockTransactionWithBlockHash(ctx, txHash, block.Hash())

View file

@ -22,6 +22,7 @@ import (
"github.com/ethereum/go-ethereum/internal/version"
"github.com/ethereum/go-ethereum/params"
"github.com/urfave/cli/v2"
)
// NewApp creates an app with sane defaults.

View file

@ -19,6 +19,7 @@ package les
import (
"fmt"
"github.com/ethereum/go-ethereum/eth/downloader/whitelist"
"strings"
"time"
@ -110,6 +111,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*LightEthereum, error) {
log.Info("")
peers := newServerPeerSet()
merger := consensus.NewMerger(chainDb)
leth := &LightEthereum{
lesCommons: lesCommons{
genesis: genesisHash,
@ -125,7 +127,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*LightEthereum, error) {
reqDist: newRequestDistributor(peers, &mclock.System{}),
accountManager: stack.AccountManager(),
merger: merger,
engine: ethconfig.CreateConsensusEngine(stack, &config.Ethash, chainConfig.Clique, nil, false, chainDb),
engine: ethconfig.CreateConsensusEngine(stack, chainConfig, config, &config.Ethash, chainConfig.Clique, nil, false, chainDb, nil),
bloomRequests: make(chan chan *bloombits.Retrieval),
bloomIndexer: core.NewBloomIndexer(chainDb, params.BloomBitsBlocksClient, params.HelperTrieConfirmations),
p2pServer: stack.Server(),

View file

@ -1,7 +1,9 @@
package miner
import (
"errors"
"github.com/ethereum/go-ethereum/core/txpool"
"github.com/ethereum/go-ethereum/trie"
"math/big"
"testing"
"time"
@ -77,13 +79,24 @@ func NewBorDefaultMiner(t *testing.T) *DefaultBorMiner {
func createBorMiner(t *testing.T, ethAPIMock api.Caller, spanner bor.Spanner, heimdallClientMock bor.IHeimdallClient, contractMock bor.GenesisContract) (*Miner, *event.TypeMux, func(skipMiner bool)) {
t.Helper()
addr0 := common.Address{0x1}
genspec := &core.Genesis{
Alloc: map[common.Address]core.GenesisAccount{
addr0: {
Balance: big.NewInt(0),
Code: []byte{0x1, 0x1},
},
},
}
// Create Ethash config
chainDB, _, chainConfig := NewDBForFakes(t)
engine := NewFakeBor(t, chainDB, chainConfig, ethAPIMock, spanner, heimdallClientMock, contractMock)
// Create Ethereum backend
bc, err := core.NewBlockChain(chainDB, nil, chainConfig, engine, vm.Config{}, nil, nil, nil)
bc, err := core.NewBlockChain(chainDB, nil, genspec, nil, engine, vm.Config{}, nil, nil, nil)
if err != nil {
t.Fatalf("can't create new chain %v", err)
}
@ -129,7 +142,7 @@ func NewDBForFakes(t TensingObject) (ethdb.Database, *core.Genesis, *params.Chai
chainDB := rawdb.NewDatabase(memdb)
genesis := core.DeveloperGenesisBlock(2, 11_500_000, common.HexToAddress("12345"))
chainConfig, _, err := core.SetupGenesisBlock(chainDB, genesis)
chainConfig, _, err := core.SetupGenesisBlock(chainDB, trie.NewDatabase(chainDB), genesis)
if err != nil {
t.Fatalf("can't create new chain config: %v", err)
}
@ -154,6 +167,54 @@ func NewFakeBor(t TensingObject, chainDB ethdb.Database, chainConfig *params.Cha
return bor.New(chainConfig, chainDB, ethAPIMock, spanner, heimdallClientMock, contractMock, false)
}
type mockBackend struct {
bc *core.BlockChain
txPool *txpool.TxPool
}
func NewMockBackend(bc *core.BlockChain, txPool *txpool.TxPool) *mockBackend {
return &mockBackend{
bc: bc,
txPool: txPool,
}
}
func (m *mockBackend) BlockChain() *core.BlockChain {
return m.bc
}
func (m *mockBackend) TxPool() *txpool.TxPool {
return m.txPool
}
func (m *mockBackend) StateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (statedb *state.StateDB, err error) {
return nil, errors.New("not supported")
}
type testBlockChain struct {
statedb *state.StateDB
gasLimit uint64
chainHeadFeed *event.Feed
}
func (bc *testBlockChain) CurrentBlock() *types.Header {
return &types.Header{
GasLimit: bc.gasLimit,
}
}
func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
return types.NewBlock(bc.CurrentBlock(), nil, nil, nil, trie.NewStackTrie(nil))
}
func (bc *testBlockChain) StateAt(common.Hash) (*state.StateDB, error) {
return bc.statedb, nil
}
func (bc *testBlockChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
return bc.chainHeadFeed.Subscribe(ch)
}
var (
// Test chain configurations
testTxPoolConfig txpool.Config

View file

@ -18,8 +18,6 @@
package miner
import (
"errors"
"math/big"
"testing"
"time"
@ -29,62 +27,12 @@ import (
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/txpool"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/trie"
)
type MockBackend struct {
bc *core.BlockChain
txPool *txpool.TxPool
}
func NewMockBackend(bc *core.BlockChain, txPool *txpool.TxPool) *mockBackend {
return &MockBackend{
bc: bc,
txPool: txPool,
}
}
func (m *MockBackend) BlockChain() *core.BlockChain {
return m.bc
}
func (m *MockBackend) TxPool() *txpool.TxPool {
return m.txPool
}
func (m *MockBackend) StateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (statedb *state.StateDB, err error) {
return nil, errors.New("not supported")
}
type testBlockChain struct {
statedb *state.StateDB
gasLimit uint64
chainHeadFeed *event.Feed
}
func (bc *testBlockChain) CurrentBlock() *types.Header {
return &types.Header{
Number: new(big.Int),
GasLimit: bc.gasLimit,
}
}
func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
return types.NewBlock(bc.CurrentBlock(), nil, nil, nil, trie.NewStackTrie(nil))
}
func (bc *testBlockChain) StateAt(common.Hash) (*state.StateDB, error) {
return bc.statedb, nil
}
func (bc *testBlockChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
return bc.chainHeadFeed.Subscribe(ch)
}
func TestMiner(t *testing.T) {
t.Parallel()

View file

@ -34,7 +34,7 @@ func TestBuildPayload(t *testing.T) {
db = rawdb.NewMemoryDatabase()
recipient = common.HexToAddress("0xdeadbeef")
)
w, b := newTestWorker(t, params.TestChainConfig, ethash.NewFaker(), db, 0)
w, b, _ := newTestWorker(t, params.TestChainConfig, ethash.NewFaker(), db, 0, false, 0, 0)
defer w.close()
timestamp := uint64(time.Now().Unix())

View file

@ -5,25 +5,27 @@ import (
"crypto/rand"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/consensus/bor"
"github.com/ethereum/go-ethereum/consensus/clique"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/txpool"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"math/big"
"os"
"sync/atomic"
"time"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
cmath "github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/common/tracing"
"github.com/ethereum/go-ethereum/consensus"
"github.com/ethereum/go-ethereum/consensus/bor"
"github.com/ethereum/go-ethereum/consensus/clique"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
@ -42,7 +44,6 @@ const (
// testGas is the gas required for contract deployment.
testGas = 144109
storageContractByteCode = "608060405234801561001057600080fd5b50610150806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80632e64cec11461003b5780636057361d14610059575b600080fd5b610043610075565b60405161005091906100a1565b60405180910390f35b610073600480360381019061006e91906100ed565b61007e565b005b60008054905090565b8060008190555050565b6000819050919050565b61009b81610088565b82525050565b60006020820190506100b66000830184610092565b92915050565b600080fd5b6100ca81610088565b81146100d557600080fd5b50565b6000813590506100e7816100c1565b92915050565b600060208284031215610103576101026100bc565b5b6000610111848285016100d8565b9150509291505056fea2646970667358221220322c78243e61b783558509c9cc22cb8493dde6925aa5e89a08cdf6e22f279ef164736f6c63430008120033"
storageContractTxCallData = "0x6057361d0000000000000000000000000000000000000000000000000000000000000001"
storageCallTxGas = 100000
@ -76,7 +77,7 @@ func init() {
// testWorkerBackend implements worker.Backend interfaces and wraps all information needed during the testing.
type testWorkerBackend struct {
DB ethdb.Database
txPool *core.TxPool
txPool *txpool.TxPool
chain *core.BlockChain
Genesis *core.Genesis
uncleBlock *types.Block
@ -109,8 +110,8 @@ func newTestWorkerBackend(t TensingObject, chainConfig *params.ChainConfig, engi
genesis := gspec.MustCommit(db)
chain, _ := core.NewBlockChain(db, &core.CacheConfig{TrieDirtyDisabled: true}, gspec.Config, engine, vm.Config{}, nil, nil, nil)
txpool := core.NewTxPool(testTxPoolConfig, chainConfig, chain)
chain, _ := core.NewBlockChain(rawdb.NewMemoryDatabase(), &core.CacheConfig{TrieDirtyDisabled: true}, &gspec, nil, engine, vm.Config{}, nil, nil, nil)
txpool := txpool.NewTxPool(testTxPoolConfig, chainConfig, chain)
// Generate a small n-block chain and an uncle block for it
if n > 0 {
@ -124,7 +125,7 @@ func newTestWorkerBackend(t TensingObject, chainConfig *params.ChainConfig, engi
parent := genesis
if n > 0 {
parent = chain.GetBlockByHash(chain.CurrentBlock().ParentHash())
parent = chain.GetBlockByHash(chain.CurrentBlock().ParentHash)
}
blocks, _ := core.GenerateChain(chainConfig, parent, engine, db, 1, func(i int, gen *core.BlockGen) {
@ -141,7 +142,7 @@ func newTestWorkerBackend(t TensingObject, chainConfig *params.ChainConfig, engi
}
func (b *testWorkerBackend) BlockChain() *core.BlockChain { return b.chain }
func (b *testWorkerBackend) TxPool() *core.TxPool { return b.txPool }
func (b *testWorkerBackend) TxPool() *txpool.TxPool { return b.txPool }
func (b *testWorkerBackend) StateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (statedb *state.StateDB, err error) {
return nil, errors.New("not supported")
}
@ -151,10 +152,10 @@ func (b *testWorkerBackend) newRandomUncle() (*types.Block, error) {
cur := b.chain.CurrentBlock()
if cur.NumberU64() == 0 {
if cur.Number.Uint64() == 0 {
parent = b.chain.Genesis()
} else {
parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash())
parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash)
}
var err error
@ -227,7 +228,7 @@ func (b *testWorkerBackend) newStorageContractCallTx(to common.Address, nonce ui
}
// NewTestWorker creates a new test worker with the given parameters.
func NewTestWorker(t TensingObject, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int, noempty uint32, delay uint, opcodeDelay uint) (*worker, *testWorkerBackend, func()) {
func NewTestWorker(t TensingObject, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int, noempty bool, delay uint, opcodeDelay uint) (*worker, *testWorkerBackend, func()) {
backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks)
backend.txPool.AddLocals(pendingTxs)
@ -244,7 +245,7 @@ func NewTestWorker(t TensingObject, chainConfig *params.ChainConfig, engine cons
w.setEtherbase(TestBankAddress)
// enable empty blocks
w.noempty = noempty
w.noempty.Store(noempty)
return w, backend, w.close
}
@ -275,9 +276,9 @@ func newWorkerWithDelay(config *Config, chainConfig *params.ChainConfig, engine
startCh: make(chan struct{}, 1),
resubmitIntervalCh: make(chan time.Duration),
resubmitAdjustCh: make(chan *intervalAdjust, resubmitAdjustChanSize),
noempty: 1,
interruptCommitFlag: config.CommitInterruptFlag,
}
worker.noempty.Store(true)
worker.profileCount = new(int32)
// Subscribe NewTxsEvent for tx pool
worker.txsSub = eth.TxPool().SubscribeNewTxsEvent(worker.txsCh)
@ -295,7 +296,7 @@ func newWorkerWithDelay(config *Config, chainConfig *params.ChainConfig, engine
}
if !worker.interruptCommitFlag {
worker.noempty = 0
worker.noempty.Store(false)
}
// Sanitize recommit interval if the user-specified one is too short.
@ -341,17 +342,22 @@ func (w *worker) mainLoopWithDelay(ctx context.Context, delay uint, opcodeDelay
for {
select {
case req := <-w.newWorkCh:
i := req.interrupt.Load()
//nolint:contextcheck
w.commitWorkWithDelay(req.ctx, req.interrupt, req.noempty, req.timestamp, delay, opcodeDelay)
w.commitWorkWithDelay(req.ctx, &i, req.noempty, req.timestamp, delay, opcodeDelay)
case req := <-w.getWorkCh:
//nolint:contextcheck
block, err := w.generateWork(req.ctx, req.params)
block, _, err := w.generateWork(req.ctx, req.params)
if err != nil {
req.err = err
req.result <- nil
} else {
req.result <- block
payload := newPayloadResult{
err: nil,
block: block,
fees: block.BaseFee(),
}
req.result <- &payload
}
case ev := <-w.chainSideCh:
@ -387,13 +393,13 @@ func (w *worker) mainLoopWithDelay(ctx context.Context, delay uint, opcodeDelay
case <-cleanTicker.C:
chainHead := w.chain.CurrentBlock()
for hash, uncle := range w.localUncles {
if uncle.NumberU64()+staleThreshold <= chainHead.NumberU64() {
if uncle.NumberU64()+staleThreshold <= chainHead.Number.Uint64() {
delete(w.localUncles, hash)
}
}
for hash, uncle := range w.remoteUncles {
if uncle.NumberU64()+staleThreshold <= chainHead.NumberU64() {
if uncle.NumberU64()+staleThreshold <= chainHead.Number.Uint64() {
delete(w.remoteUncles, hash)
}
}
@ -428,7 +434,8 @@ func (w *worker) mainLoopWithDelay(ctx context.Context, delay uint, opcodeDelay
}()
if w.interruptCommitFlag {
interruptCtx, stopFn = getInterruptTimer(ctx, w.current, w.chain.CurrentBlock())
block := w.chain.GetBlockByHash(w.chain.CurrentBlock().Hash())
interruptCtx, stopFn = getInterruptTimer(ctx, w.current, block)
// nolint : staticcheck
interruptCtx = vm.PutCache(interruptCtx, w.interruptedTxCache)
}
@ -450,9 +457,7 @@ func (w *worker) mainLoopWithDelay(ctx context.Context, delay uint, opcodeDelay
w.commitWork(ctx, nil, true, time.Now().Unix())
}
}
atomic.AddInt32(&w.newTxs, int32(len(ev.Txs)))
w.newTxs.Add(int32(len(ev.Txs)))
// System stopped
case <-w.exitCh:
return
@ -506,7 +511,8 @@ func (w *worker) commitWorkWithDelay(ctx context.Context, interrupt *int32, noem
}()
if !noempty && w.interruptCommitFlag {
interruptCtx, stopFn = getInterruptTimer(ctx, work, w.chain.CurrentBlock())
block := w.chain.GetBlockByHash(w.chain.CurrentBlock().Hash())
interruptCtx, stopFn = getInterruptTimer(ctx, work, block)
// nolint : staticcheck
interruptCtx = vm.PutCache(interruptCtx, w.interruptedTxCache)
// nolint : staticcheck
@ -525,7 +531,7 @@ func (w *worker) commitWorkWithDelay(ctx context.Context, interrupt *int32, noem
// Create an empty block based on temporary copied state for
// sealing in advance without waiting block execution finished.
if !noempty && atomic.LoadUint32(&w.noempty) == 0 {
if !noempty && !w.noempty.Load() {
err = w.commit(ctx, work.copy(), nil, false, start)
if err != nil {
return
@ -807,7 +813,8 @@ mainloop:
continue
}
// Start executing the transaction
env.state.Prepare(tx.Hash(), env.tcount)
// TODO marcello check how "Prepare" has been replaced
env.state.SetTxContext(tx.Hash(), env.tcount)
var start time.Time

View file

@ -505,6 +505,7 @@ func recalcRecommit(minRecommit, prev time.Duration, target float64, inc bool) t
}
// newWorkLoop is a standalone goroutine to submit new sealing work upon received events.
//
//nolint:gocognit
func (w *worker) newWorkLoop(ctx context.Context, recommit time.Duration) {
defer w.wg.Done()
@ -697,9 +698,7 @@ func (w *worker) mainLoop(ctx context.Context) {
acc, _ := types.Sender(w.current.signer, tx)
txs[acc] = append(txs[acc], tx)
}
// TODO marcello
// isn't this txset := types.NewTransactionsByPriceAndNonce(w.current.signer, txs, cmath.FromBig(w.current.header.BaseFee)) ?
txset := types.NewTransactionsByPriceAndNonce(w.current.signer, txs, w.current.header.BaseFee)
txset := types.NewTransactionsByPriceAndNonce(w.current.signer, txs, cmath.FromBig(w.current.header.BaseFee))
tcount := w.current.tcount
//nolint:contextcheck
@ -865,7 +864,6 @@ func (w *worker) resultLoop() {
)
})
if err != nil {
log.Error("Failed writing block to chain", "err", err)
continue
@ -1250,7 +1248,7 @@ func startProfiler(profile string, filepath string, number uint64) (func() error
if buf.Len() == 0 {
return nil
}
}
f, err := os.Create(filepath + "/" + profile + "-" + fmt.Sprint(number) + ".prof")
if err != nil {
@ -1458,7 +1456,6 @@ func (w *worker) generateWork(ctx context.Context, params *generateParams) (*typ
log.Warn("Block building is interrupted", "allowance", common.PrettyDuration(w.newpayloadTimeout))
}
}
// TODO marcello add withdrawals as last param of FinalizeAndAssemble
block, err := w.engine.FinalizeAndAssemble(ctx, w.chain, work.header, work.state, work.txs, work.unclelist(), work.receipts, params.withdrawals)
if err != nil {
return nil, nil, err
@ -1505,7 +1502,8 @@ func (w *worker) commitWork(ctx context.Context, interrupt *atomic.Int32, noempt
}()
if !noempty && w.interruptCommitFlag {
interruptCtx, stopFn = getInterruptTimer(ctx, work, w.chain.CurrentBlock())
block := w.chain.GetBlockByHash(w.chain.CurrentBlock().TxHash)
interruptCtx, stopFn = getInterruptTimer(ctx, work, block)
// nolint : staticcheck
interruptCtx = vm.PutCache(interruptCtx, w.interruptedTxCache)
}
@ -1584,7 +1582,6 @@ func getInterruptTimer(ctx context.Context, work *environment, current *types.Bl
return interruptCtx, cancel
}
// commit runs any post-transaction state modifications, assembles the final block
// and commits new work if consensus engine is running.
// Note the assumption is held that the mutation is allowed to the passed env, do

View file

@ -19,6 +19,10 @@ package miner
import (
"crypto/rand"
"errors"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
"math/big"
"os"
"sync/atomic"
@ -46,9 +50,6 @@ import (
"github.com/ethereum/go-ethereum/tests/bor/mocks"
)
// TODO marcello check redeclarations
const (
// testCode is the testing contract binary code which will initialises some
// variables in constructor
@ -58,30 +59,6 @@ const (
testGas = 144109
)
var (
// Test chain configurations
testTxPoolConfig txpool.Config
ethashChainConfig *params.ChainConfig
cliqueChainConfig *params.ChainConfig
// Test accounts
testBankKey, _ = crypto.GenerateKey()
testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
testBankFunds = big.NewInt(1000000000000000000)
testUserKey, _ = crypto.GenerateKey()
testUserAddress = crypto.PubkeyToAddress(testUserKey.PublicKey)
// Test transactions
pendingTxs []*types.Transaction
newTxs []*types.Transaction
testConfig = &Config{
Recommit: time.Second,
GasCeil: params.GenesisGasLimit,
}
)
func init() {
testTxPoolConfig = txpool.DefaultConfig
testTxPoolConfig.Journal = ""
@ -124,23 +101,52 @@ type testWorkerBackend struct {
uncleBlock *types.Block
}
func newTestWorkerBackend(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, n int) *testWorkerBackend {
// newTestWorker creates a new test worker with the given parameters.
func newTestWorker(t TensingObject, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int, noempty bool, delay uint, opcodeDelay uint) (*worker, *testWorkerBackend, func()) {
backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks)
backend.txPool.AddLocals(pendingTxs)
var w *worker
if delay != 0 || opcodeDelay != 0 {
//nolint:staticcheck
w = newWorkerWithDelay(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false, delay, opcodeDelay)
} else {
//nolint:staticcheck
w = newWorker(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false)
}
w.setEtherbase(TestBankAddress)
// enable empty blocks
w.noempty.Store(noempty)
return w, backend, w.close
}
func newTestWorkerBackend(t TensingObject, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, n int) *testWorkerBackend {
var gspec = &core.Genesis{
Config: chainConfig,
Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
Alloc: core.GenesisAlloc{TestBankAddress: {Balance: testBankFunds}},
}
switch e := engine.(type) {
case *bor.Bor:
gspec.ExtraData = make([]byte, 32+common.AddressLength+crypto.SignatureLength)
copy(gspec.ExtraData[32:32+common.AddressLength], TestBankAddress.Bytes())
e.Authorize(TestBankAddress, func(account accounts.Account, s string, data []byte) ([]byte, error) {
return crypto.Sign(crypto.Keccak256(data), testBankKey)
})
case *clique.Clique:
gspec.ExtraData = make([]byte, 32+common.AddressLength+crypto.SignatureLength)
copy(gspec.ExtraData[32:32+common.AddressLength], testBankAddress.Bytes())
e.Authorize(testBankAddress, func(account accounts.Account, s string, data []byte) ([]byte, error) {
copy(gspec.ExtraData[32:32+common.AddressLength], TestBankAddress.Bytes())
e.Authorize(TestBankAddress, func(account accounts.Account, s string, data []byte) ([]byte, error) {
return crypto.Sign(crypto.Keccak256(data), testBankKey)
})
case *ethash.Ethash:
default:
t.Fatalf("unexpected consensus engine type: %T", engine)
}
chain, err := core.NewBlockChain(db, &core.CacheConfig{TrieDirtyDisabled: true}, gspec, nil, engine, vm.Config{}, nil, nil)
chain, err := core.NewBlockChain(db, &core.CacheConfig{TrieDirtyDisabled: true}, gspec, nil, engine, vm.Config{}, nil, nil, nil)
if err != nil {
t.Fatalf("core.NewBlockChain failed: %v", err)
}
@ -150,7 +156,7 @@ func newTestWorkerBackend(t *testing.T, chainConfig *params.ChainConfig, engine
var uncle *types.Block
if n > 0 {
genDb, blocks, _ := core.GenerateChainWithGenesis(gspec, engine, n, func(i int, gen *core.BlockGen) {
gen.SetCoinbase(testBankAddress)
gen.SetCoinbase(TestBankAddress)
})
if _, err := chain.InsertChain(blocks); err != nil {
t.Fatalf("failed to insert origin chain: %v", err)
@ -181,7 +187,7 @@ func (b *testWorkerBackend) StateAtBlock(block *types.Block, reexec uint64, base
return nil, errors.New("not supported")
}
func (b *testWorkerBackend) newRandomUncle() *types.Block {
func (b *testWorkerBackend) newRandomUncle() (*types.Block, error) {
var parent *types.Block
cur := b.chain.CurrentBlock()
if cur.Number.Uint64() == 0 {
@ -189,31 +195,65 @@ func (b *testWorkerBackend) newRandomUncle() *types.Block {
} else {
parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash)
}
var err error
blocks, _ := core.GenerateChain(b.chain.Config(), parent, b.chain.Engine(), b.db, 1, func(i int, gen *core.BlockGen) {
var addr = make([]byte, common.AddressLength)
rand.Read(addr)
_, err = rand.Read(addr)
if err != nil {
return
}
gen.SetCoinbase(common.BytesToAddress(addr))
})
return blocks[0]
return blocks[0], err
}
func (b *testWorkerBackend) newRandomTx(creation bool) *types.Transaction {
var tx *types.Transaction
gasPrice := big.NewInt(10 * params.InitialBaseFee)
if creation {
tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(testBankAddress), big.NewInt(0), testGas, gasPrice, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey)
tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(TestBankAddress), big.NewInt(0), testGas, gasPrice, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey)
} else {
tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(testBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, gasPrice, nil), types.HomesteadSigner{}, testBankKey)
tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(TestBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, gasPrice, nil), types.HomesteadSigner{}, testBankKey)
}
return tx
}
func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int) (*worker, *testWorkerBackend) {
backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks)
backend.txPool.AddLocals(pendingTxs)
w := newWorker(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false)
w.setEtherbase(testBankAddress)
return w, backend
// newRandomTxWithNonce creates a new transaction with the given nonce.
func (b *testWorkerBackend) newRandomTxWithNonce(creation bool, nonce uint64) *types.Transaction {
var tx *types.Transaction
gasPrice := big.NewInt(100 * params.InitialBaseFee)
if creation {
tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(TestBankAddress), big.NewInt(0), testGas, gasPrice, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey)
} else {
tx, _ = types.SignTx(types.NewTransaction(nonce, testUserAddress, big.NewInt(1000), params.TxGas, gasPrice, nil), types.HomesteadSigner{}, testBankKey)
}
return tx
}
// newRandomTxWithGas creates a new transaction to deploy a storage smart contract.
func (b *testWorkerBackend) newStorageCreateContractTx() (*types.Transaction, common.Address) {
var tx *types.Transaction
gasPrice := big.NewInt(10 * params.InitialBaseFee)
tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(TestBankAddress), big.NewInt(0), testGas, gasPrice, common.FromHex(storageContractByteCode)), types.HomesteadSigner{}, testBankKey)
contractAddr := crypto.CreateAddress(TestBankAddress, b.txPool.Nonce(TestBankAddress))
return tx, contractAddr
}
// newStorageContractCallTx creates a new transaction to call a storage smart contract.
func (b *testWorkerBackend) newStorageContractCallTx(to common.Address, nonce uint64) *types.Transaction {
var tx *types.Transaction
gasPrice := big.NewInt(10 * params.InitialBaseFee)
tx, _ = types.SignTx(types.NewTransaction(nonce, to, nil, storageCallTxGas, gasPrice, common.FromHex(storageContractTxCallData)), types.HomesteadSigner{}, testBankKey)
return tx
}
// nolint : paralleltest
@ -241,9 +281,9 @@ func testGenerateBlockAndImport(t *testing.T, isClique bool, isBor bool) {
)
if isBor {
chainConfig = params.BorUnittestChainConfig
chainConfig = *params.BorUnittestChainConfig
engine, ctrl = getFakeBorFromConfig(t, chainConfig)
engine, ctrl = getFakeBorFromConfig(t, &chainConfig)
defer ctrl.Finish()
} else {
if isClique {
@ -258,7 +298,7 @@ func testGenerateBlockAndImport(t *testing.T, isClique bool, isBor bool) {
defer engine.Close()
w, b := newTestWorker(t, &chainConfig, engine, db, 0)
w, b, _ := newTestWorker(t, &chainConfig, engine, db, 0, false, 0, 0)
defer w.close()
// This test chain imports the mined blocks.
@ -361,7 +401,7 @@ func TestEmptyWorkClique(t *testing.T) {
func testEmptyWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
defer engine.Close()
w, _, _ := NewTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0, 0, 0, 0)
w, _, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0, false, 0, 0)
defer w.close()
var (
@ -413,7 +453,7 @@ func TestStreamUncleBlock(t *testing.T) {
ethash := ethash.NewFaker()
defer ethash.Close()
w, b, _ := NewTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1, 0, 0, 0)
w, b, _ := newTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1, false, 0, 0)
defer w.close()
var taskCh = make(chan struct{}, 3)
@ -471,7 +511,7 @@ func TestRegenerateMiningBlockClique(t *testing.T) {
func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
defer engine.Close()
w, b, _ := NewTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0, 0, 0, 0)
w, b, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0, false, 0, 0)
defer w.close()
var taskCh = make(chan struct{}, 3)
@ -535,7 +575,7 @@ func TestAdjustIntervalClique(t *testing.T) {
func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
defer engine.Close()
w, _, _ := NewTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0, 0, 0, 0)
w, _, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0, false, 0, 0)
defer w.close()
w.skipSealHook = func(task *task) bool {
@ -636,7 +676,7 @@ func TestGetSealingWorkPostMerge(t *testing.T) {
func testGetSealingWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
defer engine.Close()
w, b, _ := NewTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0, 0, 0, 0)
w, b, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0, false, 0, 0)
defer w.close()
w.setExtra([]byte{0x01, 0x02})
@ -759,7 +799,6 @@ func testGetSealingWork(t *testing.T, chainConfig *params.ChainConfig, engine co
}
}
// nolint : paralleltest
// TestCommitInterruptExperimentBor tests the commit interrupt experiment for bor consensus by inducing an artificial delay at transaction level.
func TestCommitInterruptExperimentBor(t *testing.T) {
@ -803,7 +842,7 @@ func testCommitInterruptExperimentBorContract(t *testing.T, delay uint, txCount
engine, ctrl = getFakeBorFromConfig(t, chainConfig)
w, b, _ := NewTestWorker(t, chainConfig, engine, db, 0, 1, delay, opcodeDelay)
w, b, _ := newTestWorker(t, chainConfig, engine, db, 0, true, delay, opcodeDelay)
defer func() {
w.close()
engine.Close()
@ -859,7 +898,7 @@ func testCommitInterruptExperimentBor(t *testing.T, delay uint, txCount int, opc
engine, ctrl = getFakeBorFromConfig(t, chainConfig)
w, b, _ := NewTestWorker(t, chainConfig, engine, db, 0, 1, delay, opcodeDelay)
w, b, _ := newTestWorker(t, chainConfig, engine, db, 0, true, delay, opcodeDelay)
defer func() {
w.close()
engine.Close()
@ -920,14 +959,10 @@ func BenchmarkBorMining(b *testing.B) {
chainConfig.LondonBlock = big.NewInt(0)
w, back, _ := NewTestWorker(b, chainConfig, engine, db, 0, 0, 0, 0)
w, back, _ := newTestWorker(b, chainConfig, engine, db, 0, false, 0, 0)
defer w.close()
// This test chain imports the mined blocks.
db2 := rawdb.NewMemoryDatabase()
back.Genesis.MustCommit(db2)
chain, _ := core.NewBlockChain(db2, nil, back.chain.Config(), engine, vm.Config{}, nil, nil, nil)
chain, _ := core.NewBlockChain(rawdb.NewMemoryDatabase(), nil, back.genesis, nil, engine, vm.Config{}, nil, nil, nil)
defer chain.Stop()
// Ignore empty commit here for less noise.
@ -943,7 +978,7 @@ func BenchmarkBorMining(b *testing.B) {
var err error
txInBlock := int(back.Genesis.GasLimit/totalGas) + 1
txInBlock := int(back.genesis.GasLimit/totalGas) + 1
// a bit risky
for i := 0; i < 2*totalBlocks*txInBlock; i++ {
@ -969,7 +1004,7 @@ func BenchmarkBorMining(b *testing.B) {
// Start mining!
w.start()
blockPeriod, ok := back.Genesis.Config.Bor.Period["0"]
blockPeriod, ok := back.genesis.Config.Bor.Period["0"]
if !ok {
blockPeriod = 1
}

View file

@ -116,8 +116,6 @@ func KnownDNSNetwork(genesis common.Hash, protocol string) string {
switch genesis {
case MainnetGenesisHash:
net = "mainnet"
case RinkebyGenesisHash:
net = "rinkeby"
case GoerliGenesisHash:
net = "goerli"
case MumbaiGenesisHash:

View file

@ -534,7 +534,6 @@ var (
// NetworkNames are user friendly names to use in the chain spec banner.
var NetworkNames = map[string]string{
MainnetChainConfig.ChainID.String(): "mainnet",
RinkebyChainConfig.ChainID.String(): "rinkeby",
GoerliChainConfig.ChainID.String(): "goerli",
SepoliaChainConfig.ChainID.String(): "sepolia",
BorMainnetChainConfig.ChainID.String(): "bor",

View file

@ -39,10 +39,7 @@ var flagMap = map[string][]string{
"goerli": {"BoolFlag", "No"},
"bor-mumbai": {"BoolFlag", "No"},
"bor-mainnet": {"BoolFlag", "No"},
"rinkeby": {"BoolFlag", "No"},
"ropsten": {"BoolFlag", "No"},
"sepolia": {"BoolFlag", "No"},
"kiln": {"BoolFlag", "No"},
"exitwhensynced": {"BoolFlag", "No"},
"light.serve": {"notABoolFlag", "No"},
"light.ingress": {"notABoolFlag", "No"},