diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index 1289b4c8b1..318247b6cf 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -1677,7 +1677,7 @@ var bindTests = []struct { } sim.Commit() - // This test the existence of the free retreiver call for view and pure functions + // This test the existence of the free retriever call for view and pure functions if num, err := pav.PureFunc(nil); err != nil { t.Fatalf("Failed to call anonymous field retriever: %v", err) } else if num.Cmp(big.NewInt(42)) != 0 { diff --git a/accounts/keystore/watch.go b/accounts/keystore/watch.go index 11468aaca1..20718e7f77 100644 --- a/accounts/keystore/watch.go +++ b/accounts/keystore/watch.go @@ -130,7 +130,7 @@ func (w *watcher) loop() { return } - log.Info("Filsystem watcher error", "err", err) + log.Info("Filesystem watcher error", "err", err) case <-debounce.C: w.ac.scanAccounts() diff --git a/accounts/scwallet/hub.go b/accounts/scwallet/hub.go index 062a2a770c..c01959371b 100644 --- a/accounts/scwallet/hub.go +++ b/accounts/scwallet/hub.go @@ -256,7 +256,7 @@ func (hub *Hub) refreshWallets() { continue } - // Card connected, start tracking in amongs the wallets + // Card connected, start tracking in amongst the wallets hub.wallets[reader] = wallet events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived}) } diff --git a/build/ci.go b/build/ci.go index 4f39782242..67cdf373ba 100644 --- a/build/ci.go +++ b/build/ci.go @@ -145,7 +145,7 @@ var ( // // This version is fine to be old and full of security holes, we just use it // to build the latest Go. Don't change it. If it ever becomes insufficient, - // we need to switch over to a recursive builder to jumpt across supported + // we need to switch over to a recursive builder to jump across supported // versions. gobootVersion = "1.19.6" ) diff --git a/builder/files/genesis-mainnet-v1.json b/builder/files/genesis-mainnet-v1.json index f4b2e4a6b4..11d64cabab 100644 --- a/builder/files/genesis-mainnet-v1.json +++ b/builder/files/genesis-mainnet-v1.json @@ -17,7 +17,6 @@ "bor": { "jaipurBlock": 23850000, "delhiBlock": 38189056, - "parallelUniverseBlock": 0, "indoreBlock": 44934656, "stateSyncConfirmationDelay": { "44934656": 128 diff --git a/builder/files/genesis-testnet-v4.json b/builder/files/genesis-testnet-v4.json index c848d5dce0..afad138492 100644 --- a/builder/files/genesis-testnet-v4.json +++ b/builder/files/genesis-testnet-v4.json @@ -17,7 +17,6 @@ "bor": { "jaipurBlock": 22770000, "delhiBlock": 29638656, - "parallelUniverseBlock": 0, "indoreBlock": 37075456, "stateSyncConfirmationDelay": { "37075456": 128 diff --git a/cmd/evm/testdata/3/readme.md b/cmd/evm/testdata/3/readme.md index 016887f865..7a52c9833e 100644 --- a/cmd/evm/testdata/3/readme.md +++ b/cmd/evm/testdata/3/readme.md @@ -1,6 +1,2 @@ -<<<<<<< HEAD These files examplify a transition where a transaction (executed on block 5) requests -======= -These files exemplify a transition where a transaction (executed on block 5) requests ->>>>>>> bed84606583893fdb698cc1b5058cc47b4dbd837 -the blockhash for block `1`. +the blockhash for block `1`. diff --git a/cmd/evm/testdata/4/readme.md b/cmd/evm/testdata/4/readme.md index 9d1c946a86..56846dfdd2 100644 --- a/cmd/evm/testdata/4/readme.md +++ b/cmd/evm/testdata/4/readme.md @@ -1,7 +1,3 @@ -<<<<<<< HEAD -These files examplify a transition where a transaction (executed on block 5) requests -======= These files exemplify a transition where a transaction (executed on block 5) requests ->>>>>>> bed84606583893fdb698cc1b5058cc47b4dbd837 -the blockhash for block `4`, but where the hash for that block is missing. +the blockhash for block `4`, but where the hash for that block is missing. It's expected that executing these should cause `exit` with errorcode `4`. diff --git a/consensus/bor/bor.go b/consensus/bor/bor.go index c54eef564b..40999f73c4 100644 --- a/consensus/bor/bor.go +++ b/consensus/bor/bor.go @@ -353,7 +353,7 @@ func (c *Bor) verifyHeader(chain consensus.ChainHeaderReader, header *types.Head isSprintEnd := IsSprintStart(number+1, c.config.CalculateSprint(number)) // Ensure that the extra-data contains a signer list on checkpoint, but none otherwise - signersBytes := len(header.GetValidatorBytes(c.config)) + signersBytes := len(header.GetValidatorBytes(c.chainConfig)) if !isSprintEnd && signersBytes != 0 { return errExtraValidators @@ -472,7 +472,7 @@ func (c *Bor) verifyCascadingFields(chain consensus.ChainHeaderReader, header *t sort.Sort(valset.ValidatorsByAddress(newValidators)) - headerVals, err := valset.ParseValidators(header.GetValidatorBytes(c.config)) + headerVals, err := valset.ParseValidators(header.GetValidatorBytes(c.chainConfig)) if err != nil { return err } @@ -490,7 +490,7 @@ func (c *Bor) verifyCascadingFields(chain consensus.ChainHeaderReader, header *t // verify the validator list in the last sprint block if IsSprintStart(number, c.config.CalculateSprint(number)) { - parentValidatorBytes := parent.GetValidatorBytes(c.config) + parentValidatorBytes := parent.GetValidatorBytes(c.chainConfig) validatorsBytes := make([]byte, len(snap.ValidatorSet.Validators)*validatorHeaderBytesLength) currentValidators := snap.ValidatorSet.Copy().Validators @@ -521,7 +521,7 @@ func (c *Bor) snapshot(chain consensus.ChainHeaderReader, number uint64, hash co val := valset.NewValidator(signer, 1000) validatorset := valset.NewValidatorSet([]*valset.Validator{val}) - snapshot := newSnapshot(c.config, c.signatures, number, hash, validatorset.Validators) + snapshot := newSnapshot(c.chainConfig, c.signatures, number, hash, validatorset.Validators) return snapshot, nil } @@ -541,7 +541,7 @@ func (c *Bor) snapshot(chain consensus.ChainHeaderReader, number uint64, hash co // If an on-disk checkpoint snapshot can be found, use that if number%checkpointInterval == 0 { - if s, err := loadSnapshot(c.config, c.signatures, c.db, hash); err == nil { + if s, err := loadSnapshot(c.chainConfig, c.config, c.signatures, c.db, hash); err == nil { log.Trace("Loaded snapshot from disk", "number", number, "hash", hash) snap = s @@ -570,7 +570,7 @@ func (c *Bor) snapshot(chain consensus.ChainHeaderReader, number uint64, hash co } // new snap shot - snap = newSnapshot(c.config, c.signatures, number, hash, validators) + snap = newSnapshot(c.chainConfig, c.signatures, number, hash, validators) if err := snap.store(c.db); err != nil { return nil, err } @@ -742,7 +742,7 @@ func (c *Bor) Prepare(chain consensus.ChainHeaderReader, header *types.Header) e // sort validator by address sort.Sort(valset.ValidatorsByAddress(newValidators)) - if c.config.IsParallelUniverse(header.Number) { + if c.chainConfig.IsCancun(header.Number) { var tempValidatorBytes []byte for _, validator := range newValidators { @@ -766,7 +766,7 @@ func (c *Bor) Prepare(chain consensus.ChainHeaderReader, header *types.Header) e header.Extra = append(header.Extra, validator.HeaderBytes()...) } } - } else if c.config.IsParallelUniverse(header.Number) { + } else if c.chainConfig.IsCancun(header.Number) { blockExtraData := &types.BlockExtraData{ ValidatorBytes: nil, TxDependency: nil, @@ -883,10 +883,6 @@ func (c *Bor) changeContractCodeIfNeeded(headerNumber uint64, state *state.State for addr, account := range allocs { log.Info("change contract code", "address", addr) state.SetCode(addr, account.Code) - - if state.GetBalance(addr).Cmp(big.NewInt(0)) == 0 { - state.SetBalance(addr, account.Balance) - } } } } diff --git a/consensus/bor/bor_test.go b/consensus/bor/bor_test.go index ca60d5f66f..52c93c77ad 100644 --- a/consensus/bor/bor_test.go +++ b/consensus/bor/bor_test.go @@ -40,12 +40,6 @@ func TestGenesisContractChange(t *testing.T) { "balance": "0x1000", }, }, - "6": map[string]interface{}{ - addr0.Hex(): map[string]interface{}{ - "code": hexutil.Bytes{0x1, 0x4}, - "balance": "0x2000", - }, - }, }, }, } @@ -91,35 +85,24 @@ func TestGenesisContractChange(t *testing.T) { root := genesis.Root() - // code does not change, balance remains 0 + // code does not change root, statedb = addBlock(root, 1) require.Equal(t, statedb.GetCode(addr0), []byte{0x1, 0x1}) - require.Equal(t, statedb.GetBalance(addr0), big.NewInt(0)) - // code changes 1st time, balance remains 0 + // code changes 1st time root, statedb = addBlock(root, 2) require.Equal(t, statedb.GetCode(addr0), []byte{0x1, 0x2}) - require.Equal(t, statedb.GetBalance(addr0), big.NewInt(0)) - // code same as 1st change, balance remains 0 + // code same as 1st change root, statedb = addBlock(root, 3) require.Equal(t, statedb.GetCode(addr0), []byte{0x1, 0x2}) + + // code changes 2nd time + _, statedb = addBlock(root, 4) + require.Equal(t, statedb.GetCode(addr0), []byte{0x1, 0x3}) + + // make sure balance change DOES NOT take effect require.Equal(t, statedb.GetBalance(addr0), big.NewInt(0)) - - // code changes 2nd time, balance updates to 4096 - root, statedb = addBlock(root, 4) - require.Equal(t, statedb.GetCode(addr0), []byte{0x1, 0x3}) - require.Equal(t, statedb.GetBalance(addr0), big.NewInt(4096)) - - // code same as 2nd change, balance remains 4096 - root, statedb = addBlock(root, 5) - require.Equal(t, statedb.GetCode(addr0), []byte{0x1, 0x3}) - require.Equal(t, statedb.GetBalance(addr0), big.NewInt(4096)) - - // code changes 3rd time, balance remains 4096 - _, statedb = addBlock(root, 6) - require.Equal(t, statedb.GetCode(addr0), []byte{0x1, 0x4}) - require.Equal(t, statedb.GetBalance(addr0), big.NewInt(4096)) } func TestEncodeSigHeaderJaipur(t *testing.T) { diff --git a/consensus/bor/heimdall/client.go b/consensus/bor/heimdall/client.go index d69f5ead3c..5c65721574 100644 --- a/consensus/bor/heimdall/client.go +++ b/consensus/bor/heimdall/client.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "net/url" + "path" "sort" "time" @@ -420,7 +421,7 @@ func makeURL(urlString, rawPath, rawQuery string) (*url.URL, error) { return nil, err } - u.Path = rawPath + u.Path = path.Join(u.Path, rawPath) u.RawQuery = rawQuery return u, err diff --git a/consensus/bor/heimdall/client_test.go b/consensus/bor/heimdall/client_test.go index 5023b847a5..0fa7665048 100644 --- a/consensus/bor/heimdall/client_test.go +++ b/consensus/bor/heimdall/client_test.go @@ -256,8 +256,8 @@ func TestFetchShutdown(t *testing.T) { // Expect this to fail due to timeout _, err = client.FetchCheckpoint(ctx, -1) - require.Equal(t, "context deadline exceeded", err.Error(), "expect the function error to be a context deadline exeeded error") - require.Equal(t, "context deadline exceeded", ctx.Err().Error(), "expect the ctx error to be a context deadline exeeded error") + require.Equal(t, "context deadline exceeded", err.Error(), "expect the function error to be a context deadline exceeded error") + require.Equal(t, "context deadline exceeded", ctx.Err().Error(), "expect the ctx error to be a context deadline exceeded error") cancel() @@ -346,7 +346,7 @@ func TestContext(t *testing.T) { select { case <-ctx.Done(): // Expect this to never occur, throw explicit error - errCh <- errors.New("unexpectecd call to `ctx.Done()`") + errCh <- errors.New("unexpected call to `ctx.Done()`") case <-time.After(2 * time.Second): // Case for safely exiting the tests errCh <- nil @@ -399,7 +399,7 @@ func TestSpanURL(t *testing.T) { const expected = "http://bor0/bor/span/1" if url.String() != expected { - t.Fatalf("expected URL %q, got %q", url.String(), expected) + t.Fatalf("expected URL %q, got %q", expected, url.String()) } } @@ -414,6 +414,6 @@ func TestStateSyncURL(t *testing.T) { const expected = "http://bor0/clerk/event-record/list?from-id=10&to-time=100&limit=50" if url.String() != expected { - t.Fatalf("expected URL %q, got %q", url.String(), expected) + t.Fatalf("expected URL %q, got %q", expected, url.String()) } } diff --git a/consensus/bor/snapshot.go b/consensus/bor/snapshot.go index 7ced09c3b8..87e3fb163c 100644 --- a/consensus/bor/snapshot.go +++ b/consensus/bor/snapshot.go @@ -15,8 +15,9 @@ import ( // Snapshot is the state of the authorization voting at a given point in time. type Snapshot struct { - config *params.BorConfig // Consensus engine parameters to fine tune behavior - sigcache *lru.ARCCache // Cache of recent block signatures to speed up ecrecover + chainConfig *params.ChainConfig + + sigcache *lru.ARCCache // Cache of recent block signatures to speed up ecrecover Number uint64 `json:"number"` // Block number where the snapshot was created Hash common.Hash `json:"hash"` // Block hash where the snapshot was created @@ -28,14 +29,14 @@ type Snapshot struct { // method does not initialize the set of recent signers, so only ever use if for // the genesis block. func newSnapshot( - config *params.BorConfig, + chainConfig *params.ChainConfig, sigcache *lru.ARCCache, number uint64, hash common.Hash, validators []*valset.Validator, ) *Snapshot { snap := &Snapshot{ - config: config, + chainConfig: chainConfig, sigcache: sigcache, Number: number, Hash: hash, @@ -47,7 +48,7 @@ func newSnapshot( } // loadSnapshot loads an existing snapshot from the database. -func loadSnapshot(config *params.BorConfig, sigcache *lru.ARCCache, db ethdb.Database, hash common.Hash) (*Snapshot, error) { +func loadSnapshot(chainConfig *params.ChainConfig, config *params.BorConfig, sigcache *lru.ARCCache, db ethdb.Database, hash common.Hash) (*Snapshot, error) { blob, err := db.Get(append([]byte("bor-"), hash[:]...)) if err != nil { return nil, err @@ -61,7 +62,7 @@ func loadSnapshot(config *params.BorConfig, sigcache *lru.ARCCache, db ethdb.Dat snap.ValidatorSet.UpdateValidatorMap() - snap.config = config + snap.chainConfig = chainConfig snap.sigcache = sigcache // update total voting power @@ -85,7 +86,7 @@ func (s *Snapshot) store(db ethdb.Database) error { // copy creates a deep copy of the snapshot, though not the individual votes. func (s *Snapshot) copy() *Snapshot { cpy := &Snapshot{ - config: s.config, + chainConfig: s.chainConfig, sigcache: s.sigcache, Number: s.Number, Hash: s.Hash, @@ -122,12 +123,12 @@ func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) { number := header.Number.Uint64() // Delete the oldest signer from the recent list to allow it signing again - if number >= s.config.CalculateSprint(number) { - delete(snap.Recents, number-s.config.CalculateSprint(number)) + if number >= s.chainConfig.Bor.CalculateSprint(number) { + delete(snap.Recents, number-s.chainConfig.Bor.CalculateSprint(number)) } // Resolve the authorization key and check against signers - signer, err := ecrecover(header, s.sigcache, s.config) + signer, err := ecrecover(header, s.sigcache, s.chainConfig.Bor) if err != nil { return nil, err } @@ -145,12 +146,12 @@ func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) { snap.Recents[number] = signer // change validator set and change proposer - if number > 0 && (number+1)%s.config.CalculateSprint(number) == 0 { + if number > 0 && (number+1)%s.chainConfig.Bor.CalculateSprint(number) == 0 { if err := validateHeaderExtraField(header.Extra); err != nil { return nil, err } - validatorBytes := header.GetValidatorBytes(s.config) + validatorBytes := header.GetValidatorBytes(s.chainConfig) // get validators from headers and use that for new validator set newVals, _ := valset.ParseValidators(validatorBytes) diff --git a/core/blockchain.go b/core/blockchain.go index 36d5635065..39b7fb5ec7 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -236,13 +236,14 @@ type BlockChain struct { stopping atomic.Bool // false if chain is running, true when stopped procInterrupt atomic.Bool // interrupt signaler for block processing - engine consensus.Engine - validator Validator // Block and state validator interface - prefetcher Prefetcher - processor Processor // Block transaction processor interface - parallelProcessor Processor // Parallel block transaction processor interface - forker *ForkChoice - vmConfig vm.Config + engine consensus.Engine + validator Validator // Block and state validator interface + prefetcher Prefetcher + processor Processor // Block transaction processor interface + parallelProcessor Processor // Parallel block transaction processor interface + parallelSpeculativeProcesses int // Number of parallel speculative processes + forker *ForkChoice + vmConfig vm.Config // Bor related changes borReceiptsCache *lru.Cache[common.Hash, *types.Receipt] // Cache for the most recent bor receipt receipts per block @@ -408,7 +409,8 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis // The first thing the node will do is reconstruct the verification data for // the head block (ethash cache or clique voting snapshot). Might as well do // it in advance. - bc.engine.VerifyHeader(bc, bc.CurrentHeader()) + // BOR - commented out intentionally + // bc.engine.VerifyHeader(bc, bc.CurrentHeader()) // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain for hash := range BadHashes { @@ -481,7 +483,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis } // NewParallelBlockChain , similar to NewBlockChain, creates a new blockchain object, but with a parallel state processor -func NewParallelBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis, overrides *ChainOverrides, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(header *types.Header) bool, txLookupLimit *uint64, checker ethereum.ChainValidator) (*BlockChain, error) { +func NewParallelBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis, overrides *ChainOverrides, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(header *types.Header) bool, txLookupLimit *uint64, checker ethereum.ChainValidator, numprocs int) (*BlockChain, error) { bc, err := NewBlockChain(db, cacheConfig, genesis, overrides, engine, vmConfig, shouldPreserve, txLookupLimit, checker) if err != nil { @@ -500,6 +502,7 @@ func NewParallelBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis } bc.parallelProcessor = NewParallelStateProcessor(chainConfig, bc, engine) + bc.parallelSpeculativeProcesses = numprocs return bc, nil } @@ -691,7 +694,7 @@ func (bc *BlockChain) SetHead(head uint64) error { block := bc.GetBlock(header.Hash(), header.Number.Uint64()) if block == nil { - // This should never happen. In practice, previsouly currentBlock + // This should never happen. In practice, previously currentBlock // contained the entire block whereas now only a "marker", so there // is an ever so slight chance for a race we should handle. log.Error("Current block not found in database", "block", header.Number, "hash", header.Hash()) @@ -716,7 +719,7 @@ func (bc *BlockChain) SetHeadWithTimestamp(timestamp uint64) error { block := bc.GetBlock(header.Hash(), header.Number.Uint64()) if block == nil { - // This should never happen. In practice, previsouly currentBlock + // This should never happen. In practice, previously currentBlock // contained the entire block whereas now only a "marker", so there // is an ever so slight chance for a race we should handle. log.Error("Current block not found in database", "block", header.Number, "hash", header.Hash()) @@ -2052,7 +2055,7 @@ func (bc *BlockChain) insertChain(chain types.Blocks, setHead bool) (int, error) // The chain importer is starting and stopping trie prefetchers. If a bad // block or other error is hit however, an early return may not properly // terminate the background threads. This defer ensures that we clean up - // and dangling prefetcher, without defering each and holding on live refs. + // and dangling prefetcher, without deferring each and holding on live refs. if activeState != nil { activeState.StopPrefetcher() } @@ -2139,15 +2142,6 @@ func (bc *BlockChain) insertChain(chain types.Blocks, setHead bool) (int, error) parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1) } - statedb, err := state.New(parent.Root, bc.stateCache, bc.snaps) - if err != nil { - return it.index, err - } - - // Enable prefetching to pull in trie node paths while processing transactions - statedb.StartPrefetcher("chain") - activeState = statedb - // If we have a followup block, run that against the current state to pre-cache // transactions and probabilistically some of the account/storage trie nodes. var followupInterrupt atomic.Bool diff --git a/core/blockstm/mvhashmap.go b/core/blockstm/mvhashmap.go index 59085138cf..003de91e70 100644 --- a/core/blockstm/mvhashmap.go +++ b/core/blockstm/mvhashmap.go @@ -121,34 +121,23 @@ func (mv *MVHashMap) Write(k Key, v Version, data interface{}) { return }) - cells.rw.RLock() - ci, ok := cells.tm.Get(v.TxnIndex) - cells.rw.RUnlock() - - if ok { + cells.rw.Lock() + if ci, ok := cells.tm.Get(v.TxnIndex); !ok { + cells.tm.Put(v.TxnIndex, &WriteCell{ + flag: FlagDone, + incarnation: v.Incarnation, + data: data, + }) + } else { if ci.(*WriteCell).incarnation > v.Incarnation { panic(fmt.Errorf("existing transaction value does not have lower incarnation: %v, %v", k, v.TxnIndex)) } - ci.(*WriteCell).flag = FlagDone ci.(*WriteCell).incarnation = v.Incarnation ci.(*WriteCell).data = data - } else { - cells.rw.Lock() - if ci, ok = cells.tm.Get(v.TxnIndex); !ok { - cells.tm.Put(v.TxnIndex, &WriteCell{ - flag: FlagDone, - incarnation: v.Incarnation, - data: data, - }) - } else { - ci.(*WriteCell).flag = FlagDone - ci.(*WriteCell).incarnation = v.Incarnation - ci.(*WriteCell).data = data - } - cells.rw.Unlock() } + cells.rw.Unlock() } func (mv *MVHashMap) ReadStorage(k Key, fallBack func() any) any { @@ -166,13 +155,13 @@ func (mv *MVHashMap) MarkEstimate(k Key, txIdx int) { panic(fmt.Errorf("path must already exist")) }) - cells.rw.RLock() + cells.rw.Lock() if ci, ok := cells.tm.Get(txIdx); !ok { panic(fmt.Sprintf("should not happen - cell should be present for path. TxIdx: %v, path, %x, cells keys: %v", txIdx, k, cells.tm.Keys())) } else { ci.(*WriteCell).flag = FlagEstimate } - cells.rw.RUnlock() + cells.rw.Unlock() } func (mv *MVHashMap) Delete(k Key, txIdx int) { @@ -233,8 +222,8 @@ func (mv *MVHashMap) Read(k Key, txIdx int) (res MVReadResult) { } cells.rw.RLock() + fk, fv := cells.tm.Floor(txIdx - 1) - cells.rw.RUnlock() if fk != nil && fv != nil { c := fv.(*WriteCell) @@ -253,6 +242,8 @@ func (mv *MVHashMap) Read(k Key, txIdx int) (res MVReadResult) { } } + cells.rw.RUnlock() + return } diff --git a/core/parallel_state_processor.go b/core/parallel_state_processor.go index c4077de4d8..2074c9727b 100644 --- a/core/parallel_state_processor.go +++ b/core/parallel_state_processor.go @@ -288,6 +288,11 @@ func (p *ParallelStateProcessor) Process(block *types.Block, statedb *state.Stat deps := GetDeps(blockTxDependency) + if !VerifyDeps(deps) || len(blockTxDependency) != len(block.Transactions()) { + blockTxDependency = nil + deps = make(map[int][]int) + } + if blockTxDependency != nil { metadata = true } @@ -308,63 +313,36 @@ func (p *ParallelStateProcessor) Process(block *types.Block, statedb *state.Stat shouldDelayFeeCal = false } - if len(blockTxDependency) != len(block.Transactions()) { - task := &ExecutionTask{ - msg: *msg, - config: p.config, - gasLimit: block.GasLimit(), - blockNumber: blockNumber, - blockHash: blockHash, - tx: tx, - index: i, - cleanStateDB: cleansdb, - finalStateDB: statedb, - blockChain: p.bc, - header: header, - evmConfig: cfg, - shouldDelayFeeCal: &shouldDelayFeeCal, - sender: msg.From, - totalUsedGas: usedGas, - receipts: &receipts, - allLogs: &allLogs, - dependencies: deps[i], - coinbase: coinbase, - blockContext: blockContext, - } - - tasks = append(tasks, task) - } else { - task := &ExecutionTask{ - msg: *msg, - config: p.config, - gasLimit: block.GasLimit(), - blockNumber: blockNumber, - blockHash: blockHash, - tx: tx, - index: i, - cleanStateDB: cleansdb, - finalStateDB: statedb, - blockChain: p.bc, - header: header, - evmConfig: cfg, - shouldDelayFeeCal: &shouldDelayFeeCal, - sender: msg.From, - totalUsedGas: usedGas, - receipts: &receipts, - allLogs: &allLogs, - dependencies: nil, - coinbase: coinbase, - blockContext: blockContext, - } - - tasks = append(tasks, task) + task := &ExecutionTask{ + msg: *msg, + config: p.config, + gasLimit: block.GasLimit(), + blockNumber: blockNumber, + blockHash: blockHash, + tx: tx, + index: i, + cleanStateDB: cleansdb, + finalStateDB: statedb, + blockChain: p.bc, + header: header, + evmConfig: cfg, + shouldDelayFeeCal: &shouldDelayFeeCal, + sender: msg.From, + totalUsedGas: usedGas, + receipts: &receipts, + allLogs: &allLogs, + dependencies: deps[i], + coinbase: coinbase, + blockContext: blockContext, } + + tasks = append(tasks, task) } backupStateDB := statedb.Copy() profile := false - result, err := blockstm.ExecuteParallel(tasks, profile, metadata, cfg.ParallelSpeculativeProcesses, interruptCtx) + result, err := blockstm.ExecuteParallel(tasks, profile, metadata, p.bc.parallelSpeculativeProcesses, interruptCtx) if err == nil && profile && result.Deps != nil { _, weight := result.Deps.LongestPath(*result.Stats) @@ -398,7 +376,7 @@ func (p *ParallelStateProcessor) Process(block *types.Block, statedb *state.Stat t.totalUsedGas = usedGas } - _, err = blockstm.ExecuteParallel(tasks, false, metadata, cfg.ParallelSpeculativeProcesses, interruptCtx) + _, err = blockstm.ExecuteParallel(tasks, false, metadata, p.bc.parallelSpeculativeProcesses, interruptCtx) break } @@ -427,3 +405,21 @@ func GetDeps(txDependency [][]uint64) map[int][]int { return deps } + +// returns true if dependencies are correct +func VerifyDeps(deps map[int][]int) bool { + // number of transactions in the block + n := len(deps) + + // Handle out-of-range and circular dependency problem + for i := 0; i <= n-1; i++ { + val := deps[i] + for _, depTx := range val { + if depTx >= n || depTx >= i { + return false + } + } + } + + return true +} diff --git a/core/parallel_state_processor_test.go b/core/parallel_state_processor_test.go new file mode 100644 index 0000000000..424ea4282a --- /dev/null +++ b/core/parallel_state_processor_test.go @@ -0,0 +1,30 @@ +package core + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestMetadata(t *testing.T) { + t.Parallel() + + correctTxDependency := [][]uint64{{}, {0}, {}, {1}, {3}, {}, {0, 2}, {5}, {}, {8}} + wrongTxDependency := [][]uint64{{0}} + wrongTxDependencyCircular := [][]uint64{{}, {2}, {1}} + wrongTxDependencyOutOfRange := [][]uint64{{}, {}, {3}} + + var temp map[int][]int + + temp = GetDeps(correctTxDependency) + assert.Equal(t, true, VerifyDeps(temp)) + + temp = GetDeps(wrongTxDependency) + assert.Equal(t, false, VerifyDeps(temp)) + + temp = GetDeps(wrongTxDependencyCircular) + assert.Equal(t, false, VerifyDeps(temp)) + + temp = GetDeps(wrongTxDependencyOutOfRange) + assert.Equal(t, false, VerifyDeps(temp)) +} diff --git a/core/rawdb/bor_receipt.go b/core/rawdb/bor_receipt.go index 456000f821..68a436a081 100644 --- a/core/rawdb/bor_receipt.go +++ b/core/rawdb/bor_receipt.go @@ -76,7 +76,7 @@ func ReadRawBorReceipt(db ethdb.Reader, hash common.Hash, number uint64) *types. } // ReadBorReceipt retrieves all the bor block receipts belonging to a block, including -// its correspoinding metadata fields. If it is unable to populate these metadata +// its corresponding metadata fields. If it is unable to populate these metadata // fields then nil is returned. func ReadBorReceipt(db ethdb.Reader, hash common.Hash, number uint64, config *params.ChainConfig) *types.Receipt { if config != nil && config.Bor != nil && config.Bor.Sprint != nil && !config.Bor.IsSprintStart(number) { diff --git a/core/rawdb/database.go b/core/rawdb/database.go index 3aaa6fcf3e..ac88e7eb8e 100644 --- a/core/rawdb/database.go +++ b/core/rawdb/database.go @@ -259,7 +259,7 @@ func NewDatabaseWithFreezer(db ethdb.KeyValueStore, ancient string, namespace st break } } - // We are about to exit on error. Print database metdata beore exiting + // We are about to exit on error. Print database metadata before exiting printChainMetadata(db) return nil, fmt.Errorf("gap in the chain between ancients [0 - #%d] and leveldb [#%d - #%d] ", @@ -669,7 +669,7 @@ func printChainMetadata(db ethdb.KeyValueStore) { fmt.Fprintf(os.Stderr, "\n\n") } -// ReadChainMetadata returns a set of key/value pairs that contains informatin +// ReadChainMetadata returns a set of key/value pairs that contains information // about the database chain status. This can be used for diagnostic purposes // when investigating the state of the node. func ReadChainMetadata(db ethdb.KeyValueStore) [][]string { diff --git a/core/rawdb/databases_64bit.go b/core/rawdb/databases_64bit.go index ae2ba7f2a0..9d7a620d5c 100644 --- a/core/rawdb/databases_64bit.go +++ b/core/rawdb/databases_64bit.go @@ -23,7 +23,7 @@ import ( "github.com/ethereum/go-ethereum/ethdb/pebble" ) -// Pebble is unsuported on 32bit architecture +// Pebble is unsupported on 32bit architecture const PebbleEnabled = true // NewPebbleDBDatabase creates a persistent key-value database without a freezer diff --git a/core/rawdb/freezer_table_test.go b/core/rawdb/freezer_table_test.go index d680b41c29..c5f1e32c80 100644 --- a/core/rawdb/freezer_table_test.go +++ b/core/rawdb/freezer_table_test.go @@ -917,7 +917,7 @@ func getChunk(size int, b int) []byte { } // TODO (?) -// - test that if we remove several head-files, aswell as data last data-file, +// - test that if we remove several head-files, as well as data last data-file, // the index is truncated accordingly // Right now, the freezer would fail on these conditions: // 1. have data files d0, d1, d2, d3 diff --git a/core/state/pruner/pruner.go b/core/state/pruner/pruner.go index 157d2e181d..5a4fb8a1b7 100644 --- a/core/state/pruner/pruner.go +++ b/core/state/pruner/pruner.go @@ -85,14 +85,12 @@ func NewPruner(db ethdb.Database, config Config) (*Pruner, error) { if headBlock == nil { return nil, errors.New("failed to load head block") } - snapconfig := snapshot.Config{ CacheSize: 256, Recovery: false, NoBuild: true, AsyncBuild: false, } - snaptree, err := snapshot.New(snapconfig, db, trie.NewDatabase(db), headBlock.Root()) if err != nil { return nil, err // The relevant snapshot(s) might not exist @@ -102,12 +100,10 @@ func NewPruner(db ethdb.Database, config Config) (*Pruner, error) { log.Warn("Sanitizing bloomfilter size", "provided(MB)", config.BloomSize, "updated(MB)", 256) config.BloomSize = 256 } - stateBloom, err := newStateBloomWithSize(config.BloomSize) if err != nil { return nil, err } - return &Pruner{ config: config, chainHeader: headBlock.Header(), @@ -122,7 +118,7 @@ func prune(snaptree *snapshot.Tree, root common.Hash, maindb ethdb.Database, sta // the trie nodes(and codes) belong to the active state will be filtered // out. A very small part of stale tries will also be filtered because of // the false-positive rate of bloom filter. But the assumption is held here - // that the false-positive is low enough(~0.05%). The probablity of the + // that the false-positive is low enough(~0.05%). The probability of the // dangling node is the state root is super low. So the dangling nodes in // theory will never ever be visited again. var ( @@ -133,7 +129,6 @@ func prune(snaptree *snapshot.Tree, root common.Hash, maindb ethdb.Database, sta batch = maindb.NewBatch() iter = maindb.NewIterator(nil, nil) ) - for iter.Next() { key := iter.Key() @@ -147,7 +142,6 @@ func prune(snaptree *snapshot.Tree, root common.Hash, maindb ethdb.Database, sta if isCode { checkKey = codeKey } - if _, exist := middleStateRoots[common.BytesToHash(checkKey)]; exist { log.Debug("Forcibly delete the middle state roots", "hash", common.BytesToHash(checkKey)) } else { @@ -155,26 +149,21 @@ func prune(snaptree *snapshot.Tree, root common.Hash, maindb ethdb.Database, sta continue } } - count += 1 size += common.StorageSize(len(key) + len(iter.Value())) batch.Delete(key) var eta time.Duration // Realistically will never remain uninited - if done := binary.BigEndian.Uint64(key[:8]); done > 0 { var ( left = math.MaxUint64 - binary.BigEndian.Uint64(key[:8]) speed = done/uint64(time.Since(pstart)/time.Millisecond+1) + 1 // +1s to avoid division by zero ) - eta = time.Duration(left/speed) * time.Millisecond } - if time.Since(logged) > 8*time.Second { log.Info("Pruning state data", "nodes", count, "size", size, "elapsed", common.PrettyDuration(time.Since(pstart)), "eta", common.PrettyDuration(eta)) - logged = time.Now() } // Recreate the iterator after every batch commit in order @@ -188,12 +177,10 @@ func prune(snaptree *snapshot.Tree, root common.Hash, maindb ethdb.Database, sta } } } - if batch.ValueSize() > 0 { batch.Write() batch.Reset() } - iter.Release() log.Info("Pruned state data", "nodes", count, "size", size, "elapsed", common.PrettyDuration(time.Since(pstart))) @@ -220,19 +207,15 @@ func prune(snaptree *snapshot.Tree, root common.Hash, maindb ethdb.Database, sta // Note for small pruning, the compaction is skipped. if count >= rangeCompactionThreshold { cstart := time.Now() - for b := 0x00; b <= 0xf0; b += 0x10 { var ( start = []byte{byte(b)} end = []byte{byte(b + 0x10)} ) - if b == 0xf0 { end = nil } - log.Info("Compacting database", "range", fmt.Sprintf("%#x-%#x", start, end), "elapsed", common.PrettyDuration(time.Since(cstart))) - if err := maindb.Compact(start, end); err != nil { log.Error("Database compaction failed", "error", err) return err @@ -240,16 +223,13 @@ func prune(snaptree *snapshot.Tree, root common.Hash, maindb ethdb.Database, sta } log.Info("Database compaction finished", "elapsed", common.PrettyDuration(time.Since(cstart))) } - log.Info("State pruning successful", "pruned", size, "elapsed", common.PrettyDuration(time.Since(start))) - return nil } // Prune deletes all historical state nodes except the nodes belong to the // specified state version. If user doesn't specify the state version, use // the bottom-most snapshot diff layer as the target. -// nolint:nestif func (p *Pruner) Prune(root common.Hash) error { // If the state bloom filter is already committed previously, // reuse it for pruning instead of generating a new one. It's @@ -259,7 +239,6 @@ func (p *Pruner) Prune(root common.Hash) error { if err != nil { return err } - if stateBloomRoot != (common.Hash{}) { return RecoverPruning(p.config.Datadir, p.db) } @@ -298,23 +277,18 @@ func (p *Pruner) Prune(root common.Hash) error { // state available, but we don't want to use the topmost state // as the pruning target. var found bool - for i := len(layers) - 2; i >= 2; i-- { if rawdb.HasLegacyTrieNode(p.db, layers[i].Root()) { root = layers[i].Root() found = true - log.Info("Selecting middle-layer as the pruning target", "root", root, "depth", i) - break } } - if !found { if len(layers) > 0 { return errors.New("no snapshot paired state") } - return fmt.Errorf("associated state[%x] is not present", root) } } else { @@ -327,18 +301,15 @@ func (p *Pruner) Prune(root common.Hash) error { // All the state roots of the middle layer should be forcibly pruned, // otherwise the dangling state will be left. middleRoots := make(map[common.Hash]struct{}) - for _, layer := range layers { if layer.Root() == root { break } - middleRoots[layer.Root()] = struct{}{} } // Traverse the target state, re-construct the whole state trie and // commit to the given bloom filter. start := time.Now() - if err := snapshot.GenerateTrie(p.snaptree, root, p.db, p.stateBloom); err != nil { return err } @@ -347,17 +318,13 @@ func (p *Pruner) Prune(root common.Hash) error { if err := extractGenesis(p.db, p.stateBloom); err != nil { return err } - filterName := bloomFilterName(p.config.Datadir, root) log.Info("Writing state bloom to disk", "name", filterName) - if err := p.stateBloom.Commit(filterName, filterName+stateBloomFileTempSuffix); err != nil { return err } - log.Info("State bloom filter committed", "name", filterName) - return prune(p.snaptree, root, p.db, p.stateBloom, filterName, middleRoots, start) } @@ -373,11 +340,9 @@ func RecoverPruning(datadir string, db ethdb.Database) error { if err != nil { return err } - if stateBloomPath == "" { return nil // nothing to recover } - headBlock := rawdb.ReadHeadBlock(db) if headBlock == nil { return errors.New("failed to load head block") @@ -396,17 +361,14 @@ func RecoverPruning(datadir string, db ethdb.Database) error { NoBuild: true, AsyncBuild: false, } - snaptree, err := snapshot.New(snapconfig, db, trie.NewDatabase(db), headBlock.Root()) if err != nil { return err // The relevant snapshot(s) might not exist } - stateBloom, err := NewStateBloomFromDisk(stateBloomPath) if err != nil { return err } - log.Info("Loaded state bloom filter", "path", stateBloomPath) // All the state roots of the middle layers should be forcibly pruned, @@ -416,21 +378,17 @@ func RecoverPruning(datadir string, db ethdb.Database) error { layers = snaptree.Snapshots(headBlock.Root(), 128, true) middleRoots = make(map[common.Hash]struct{}) ) - for _, layer := range layers { if layer.Root() == stateBloomRoot { found = true break } - middleRoots[layer.Root()] = struct{}{} } - if !found { log.Error("Pruning target state is not existent") return errors.New("non-existent target state") } - return prune(snaptree, stateBloomRoot, db, stateBloom, stateBloomPath, middleRoots, time.Now()) } @@ -441,12 +399,10 @@ func extractGenesis(db ethdb.Database, stateBloom *stateBloom) error { if genesisHash == (common.Hash{}) { return errors.New("missing genesis hash") } - genesis := rawdb.ReadBlock(db, genesisHash, 0) if genesis == nil { return errors.New("missing genesis block") } - t, err := trie.NewStateTrie(trie.StateTrieID(genesis.Root()), trie.NewDatabase(db)) if err != nil { return err @@ -469,10 +425,8 @@ func extractGenesis(db ethdb.Database, stateBloom *stateBloom) error { if err := rlp.DecodeBytes(accIter.LeafBlob(), &acc); err != nil { return err } - if acc.Root != types.EmptyRootHash { id := trie.StorageTrieID(genesis.Root(), common.BytesToHash(accIter.LeafKey()), acc.Root) - storageTrie, err := trie.NewStateTrie(id, trie.NewDatabase(db)) if err != nil { return err @@ -487,18 +441,15 @@ func extractGenesis(db ethdb.Database, stateBloom *stateBloom) error { stateBloom.Put(hash.Bytes(), nil) } } - if storageIter.Error() != nil { return storageIter.Error() } } - if !bytes.Equal(acc.CodeHash, types.EmptyCodeHash.Bytes()) { stateBloom.Put(acc.CodeHash, nil) } } } - return accIter.Error() } @@ -511,7 +462,6 @@ func isBloomFilter(filename string) (bool, common.Hash) { if strings.HasPrefix(filename, stateBloomFilePrefix) && strings.HasSuffix(filename, stateBloomFileSuffix) { return true, common.HexToHash(filename[len(stateBloomFilePrefix)+1 : len(filename)-len(stateBloomFileSuffix)-1]) } - return false, common.Hash{} } @@ -520,7 +470,6 @@ func findBloomFilter(datadir string) (string, common.Hash, error) { stateBloomPath string stateBloomRoot common.Hash ) - if err := filepath.Walk(datadir, func(path string, info os.FileInfo, err error) error { if info != nil && !info.IsDir() { ok, root := isBloomFilter(path) @@ -533,6 +482,5 @@ func findBloomFilter(datadir string) (string, common.Hash, error) { }); err != nil { return "", common.Hash{}, err } - return stateBloomPath, stateBloomRoot, nil } diff --git a/core/state/snapshot/difflayer.go b/core/state/snapshot/difflayer.go index 2df11a88f7..76fce22d1c 100644 --- a/core/state/snapshot/difflayer.go +++ b/core/state/snapshot/difflayer.go @@ -43,7 +43,7 @@ var ( aggregatorMemoryLimit = uint64(4 * 1024 * 1024) // aggregatorItemLimit is an approximate number of items that will end up - // in the agregator layer before it's flushed out to disk. A plain account + // in the aggregator layer before it's flushed out to disk. A plain account // weighs around 14B (+hash), a storage slot 32B (+hash), a deleted slot // 0B (+hash). Slots are mostly set/unset in lockstep, so that average at // 16B (+hash). All in all, the average entry seems to be 15+32=47B. Use a diff --git a/core/state/snapshot/disklayer_test.go b/core/state/snapshot/disklayer_test.go index 29e7e37a85..79d920eaba 100644 --- a/core/state/snapshot/disklayer_test.go +++ b/core/state/snapshot/disklayer_test.go @@ -141,7 +141,7 @@ func TestDiskMerge(t *testing.T) { // Retrieve all the data through the disk layer and validate it base = snaps.Snapshot(diffRoot) if _, ok := base.(*diskLayer); !ok { - t.Fatalf("update not flattend into the disk layer") + t.Fatalf("update not flattened into the disk layer") } // assertAccount ensures that an account matches the given blob. @@ -374,7 +374,7 @@ func TestDiskPartialMerge(t *testing.T) { // Retrieve all the data through the disk layer and validate it base = snaps.Snapshot(diffRoot) if _, ok := base.(*diskLayer); !ok { - t.Fatalf("test %d: update not flattend into the disk layer", i) + t.Fatalf("test %d: update not flattened into the disk layer", i) } assertAccount(accNoModNoCache, accNoModNoCache[:]) diff --git a/core/state/sync_test.go b/core/state/sync_test.go index d9f7736680..7e4bf9cb3e 100644 --- a/core/state/sync_test.go +++ b/core/state/sync_test.go @@ -229,7 +229,7 @@ func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) { stTrie, err := trie.New(id, srcDb.TrieDB()) if err != nil { - t.Fatalf("failed to retriev storage trie for path %x: %v", node.syncPath[1], err) + t.Fatalf("failed to retrieve storage trie for path %x: %v", node.syncPath[1], err) } data, _, err := stTrie.GetNode(node.syncPath[1]) diff --git a/core/txpool/blobpool/blobpool.go b/core/txpool/blobpool/blobpool.go index 8edca18122..d3ada76e82 100644 --- a/core/txpool/blobpool/blobpool.go +++ b/core/txpool/blobpool/blobpool.go @@ -458,7 +458,7 @@ func (p *BlobPool) parseTransaction(id uint64, size uint32, blob []byte) error { item := new(blobTx) if err := rlp.DecodeBytes(blob, item); err != nil { // This path is impossible unless the disk data representation changes - // across restarts. For that ever unprobable case, recover gracefully + // across restarts. For that ever improbable case, recover gracefully // by ignoring this data entry. log.Error("Failed to decode blob pool entry", "id", id, "err", err) return err @@ -468,7 +468,7 @@ func (p *BlobPool) parseTransaction(id uint64, size uint32, blob []byte) error { sender, err := p.signer.Sender(item.Tx) if err != nil { // This path is impossible unless the signature validity changes across - // restarts. For that ever unprobable case, recover gracefully by ignoring + // restarts. For that ever improbable case, recover gracefully by ignoring // this data entry. log.Error("Failed to recover blob tx sender", "id", id, "hash", item.Tx.Hash(), "err", err) return err @@ -708,7 +708,7 @@ func (p *BlobPool) recheck(addr common.Address, inclusions map[common.Hash]uint6 // offload removes a tracked blob transaction from the pool and moves it into the // limbo for tracking until finality. // -// The method may log errors for various unexpcted scenarios but will not return +// The method may log errors for various unexpected scenarios but will not return // any of it since there's no clear error case. Some errors may be due to coding // issues, others caused by signers mining MEV stuff or swapping transactions. In // all cases, the pool needs to continue operating. @@ -735,7 +735,7 @@ func (p *BlobPool) offload(addr common.Address, nonce uint64, id uint64, inclusi } // Reset implements txpool.SubPool, allowing the blob pool's internal state to be -// kept in sync with the main transacion pool's internal state. +// kept in sync with the main transaction pool's internal state. func (p *BlobPool) Reset(oldHead, newHead *types.Header) { waitStart := time.Now() p.lock.Lock() @@ -939,7 +939,7 @@ func (p *BlobPool) reinject(addr common.Address, tx *types.Transaction) { log.Error("Failed to write transaction into storage", "hash", tx.Hash(), "err", err) return } - // Update the indixes and metrics + // Update the indexes and metrics meta := newBlobTxMeta(id, p.store.Size(id), tx) if _, ok := p.index[addr]; !ok { @@ -959,7 +959,7 @@ func (p *BlobPool) reinject(addr common.Address, tx *types.Transaction) { } // SetGasTip implements txpool.SubPool, allowing the blob pool's gas requirements -// to be kept in sync with the main transacion pool's gas requirements. +// to be kept in sync with the main transaction pool's gas requirements. func (p *BlobPool) SetGasTip(tip *big.Int) { p.lock.Lock() defer p.lock.Unlock() @@ -1153,7 +1153,7 @@ func (p *BlobPool) Get(hash common.Hash) *txpool.Transaction { } // Add inserts a set of blob transactions into the pool if they pass validation (both -// consensus validity and pool restictions). +// consensus validity and pool restrictions). func (p *BlobPool) Add(txs []*txpool.Transaction, local bool, sync bool) []error { errs := make([]error, len(txs)) for i, tx := range txs { @@ -1163,7 +1163,7 @@ func (p *BlobPool) Add(txs []*txpool.Transaction, local bool, sync bool) []error } // Add inserts a new blob transaction into the pool if it passes validation (both -// consensus validity and pool restictions). +// consensus validity and pool restrictions). func (p *BlobPool) add(tx *types.Transaction, blobs []kzg4844.Blob, commits []kzg4844.Commitment, proofs []kzg4844.Proof) (err error) { // The blob pool blocks on adding a transaction. This is because blob txs are // only even pulled form the network, so this method will act as the overload diff --git a/core/txpool/blobpool/blobpool_test.go b/core/txpool/blobpool/blobpool_test.go index 33826c7338..9e33eaefef 100644 --- a/core/txpool/blobpool/blobpool_test.go +++ b/core/txpool/blobpool/blobpool_test.go @@ -593,9 +593,9 @@ func TestOpenDrops(t *testing.T) { verifyPoolInternals(t, pool) } -// Tests that transactions loaded from disk are indexed corrently. +// Tests that transactions loaded from disk are indexed correctly. // -// - 1. Transactions must be groupped by sender, sorted by nonce +// - 1. Transactions must be grouped by sender, sorted by nonce // - 2. Eviction thresholds are calculated correctly for the sequences // - 3. Balance usage of an account is totals across all transactions func TestOpenIndex(t *testing.T) { @@ -1208,7 +1208,7 @@ func TestAdd(t *testing.T) { keys[acc], _ = crypto.GenerateKey() addrs[acc] = crypto.PubkeyToAddress(keys[acc].PublicKey) - // Seed the state database with this acocunt + // Seed the state database with this account statedb.AddBalance(addrs[acc], new(big.Int).SetUint64(seed.balance)) statedb.SetNonce(addrs[acc], seed.nonce) diff --git a/core/txpool/blobpool/limbo.go b/core/txpool/blobpool/limbo.go index 4cb5042c2b..e7f49109bf 100644 --- a/core/txpool/blobpool/limbo.go +++ b/core/txpool/blobpool/limbo.go @@ -57,7 +57,7 @@ func newLimbo(datadir string) (*limbo, error) { index: make(map[common.Hash]uint64), groups: make(map[uint64]map[uint64]common.Hash), } - // Index all limboed blobs on disk and delete anything inprocessable + // Index all limboed blobs on disk and delete anything unprocessable var fails []uint64 index := func(id uint64, size uint32, data []byte) { if l.parseBlob(id, data) != nil { @@ -93,7 +93,7 @@ func (l *limbo) parseBlob(id uint64, data []byte) error { item := new(limboBlob) if err := rlp.DecodeBytes(data, item); err != nil { // This path is impossible unless the disk data representation changes - // across restarts. For that ever unprobable case, recover gracefully + // across restarts. For that ever improbable case, recover gracefully // by ignoring this data entry. log.Error("Failed to decode blob limbo entry", "id", id, "err", err) return err @@ -176,7 +176,7 @@ func (l *limbo) pull(tx common.Hash) ([]kzg4844.Blob, []kzg4844.Commitment, []kz // update changes the block number under which a blob transaction is tracked. This // method should be used when a reorg changes a transaction's inclusion block. // -// The method may log errors for various unexpcted scenarios but will not return +// The method may log errors for various unexpected scenarios but will not return // any of it since there's no clear error case. Some errors may be due to coding // issues, others caused by signers mining MEV stuff or swapping transactions. In // all cases, the pool needs to continue operating. @@ -195,7 +195,7 @@ func (l *limbo) update(tx common.Hash, block uint64) { log.Trace("Blob transaction unchanged in limbo", "tx", tx, "block", block) return } - // Retrieve the old blobs from the data store and write tehm back with a new + // Retrieve the old blobs from the data store and write them back with a new // block number. IF anything fails, there's not much to do, go on. item, err := l.getAndDrop(id) if err != nil { diff --git a/core/txpool/blobpool/metrics.go b/core/txpool/blobpool/metrics.go index 070cc5ca47..587804cc61 100644 --- a/core/txpool/blobpool/metrics.go +++ b/core/txpool/blobpool/metrics.go @@ -65,7 +65,7 @@ var ( pooltipGauge = metrics.NewRegisteredGauge("blobpool/pooltip", nil) // addwait/time, resetwait/time and getwait/time track the rough health of - // the pool and wether or not it's capable of keeping up with the load from + // the pool and whether or not it's capable of keeping up with the load from // the network. addwaitHist = metrics.NewRegisteredHistogram("blobpool/addwait", nil, metrics.NewExpDecaySample(1028, 0.015)) addtimeHist = metrics.NewRegisteredHistogram("blobpool/addtime", nil, metrics.NewExpDecaySample(1028, 0.015)) diff --git a/core/txpool/legacypool/legacypool.go b/core/txpool/legacypool/legacypool.go index d37f5ef4bc..47cac42eb2 100644 --- a/core/txpool/legacypool/legacypool.go +++ b/core/txpool/legacypool/legacypool.go @@ -159,8 +159,7 @@ var DefaultConfig = Config{ AccountQueue: 64, GlobalQueue: 1024, - Lifetime: 3 * time.Hour, - AllowUnprotectedTxs: false, + Lifetime: 3 * time.Hour, } // sanitize checks the provided user configurations and changes anything that's @@ -420,7 +419,7 @@ func (pool *LegacyPool) Close() error { } // Reset implements txpool.SubPool, allowing the legacy pool's internal state to be -// kept in sync with the main transacion pool's internal state. +// kept in sync with the main transaction pool's internal state. func (pool *LegacyPool) Reset(oldHead, newHead *types.Header) { wait := pool.requestReset(oldHead, newHead) <-wait @@ -591,8 +590,7 @@ func (pool *LegacyPool) local() map[common.Address]types.Transactions { // and does not require the pool mutex to be held. func (pool *LegacyPool) validateTxBasics(tx *types.Transaction, local bool) error { opts := &txpool.ValidationOptions{ - Config: pool.chainconfig, - AllowUnprotectedTxs: pool.config.AllowUnprotectedTxs, + Config: pool.chainconfig, Accept: 0 | 1<= 0; i-- { if pastChain[i].Number.Uint64() == number { res := pastChain[i].Hash() == hash @@ -205,7 +205,7 @@ func isValidChain(currentHeader *types.Header, chain []*types.Header, doExist bo // FIXME: remoteHeader is not used func isValidPeer(fetchHeadersByNumber func(number uint64, amount int, skip int, reverse bool) ([]*types.Header, []common.Hash, error), doExist bool, number uint64, hash common.Hash) (bool, error) { - // Check for availaibility of the last milestone block. + // Check for availability of the last milestone block. // This can be also be empty if our heimdall is not responding // or we're running without it. if !doExist { diff --git a/eth/downloader/whitelist/service_test.go b/eth/downloader/whitelist/service_test.go index f37af30f0c..aace6ff0e0 100644 --- a/eth/downloader/whitelist/service_test.go +++ b/eth/downloader/whitelist/service_test.go @@ -240,13 +240,13 @@ func TestMilestone(t *testing.T) { require.Equal(t, order[0], uint64(16), "expected number to be 16 but got", order[0]) require.Equal(t, list[order[0]], common.Hash{16}, "expected value is", common.Hash{16}.String()[2:], "but got", list[order[0]]) - capicity := milestone.MaxCapacity - for i := 16; i <= 16*(capicity+1); i = i + 16 { + capacity := milestone.MaxCapacity + for i := 16; i <= 16*(capacity+1); i = i + 16 { s.ProcessFutureMilestone(uint64(i), common.Hash{16}) } - require.Equal(t, len(milestone.FutureMilestoneOrder), capicity, "expected length is", capicity) - require.Equal(t, milestone.FutureMilestoneOrder[capicity-1], uint64(16*capicity), "expected value is", uint64(16*capicity), "but got", milestone.FutureMilestoneOrder[capicity-1]) + require.Equal(t, len(milestone.FutureMilestoneOrder), capacity, "expected length is", capacity) + require.Equal(t, milestone.FutureMilestoneOrder[capacity-1], uint64(16*capacity), "expected value is", uint64(16*capacity), "but got", milestone.FutureMilestoneOrder[capacity-1]) } // TestIsValidPeer checks the IsValidPeer function in isolation diff --git a/eth/protocols/eth/dispatcher.go b/eth/protocols/eth/dispatcher.go index 3c0f36fc08..23fd05157c 100644 --- a/eth/protocols/eth/dispatcher.go +++ b/eth/protocols/eth/dispatcher.go @@ -41,7 +41,7 @@ var ( // Request is a pending request to allow tracking it and delivering a response // back to the requester on their chosen channel. type Request struct { - peer *Peer // Peer to which this request belogs for untracking + peer *Peer // Peer to which this request belongs for untracking id uint64 // Request ID to match up replies to sink chan *Response // Channel to deliver the response on @@ -228,7 +228,7 @@ func (p *Peer) dispatcher() { switch { case res.Req == nil: // Response arrived with an untracked ID. Since even cancelled - // requests are tracked until fulfilment, a dangling response + // requests are tracked until fulfillment, a dangling response // means the remote peer implements the protocol badly. resOp.fail <- errDanglingResponse diff --git a/eth/protocols/eth/peer.go b/eth/protocols/eth/peer.go index 219f486c8e..45236fea8e 100644 --- a/eth/protocols/eth/peer.go +++ b/eth/protocols/eth/peer.go @@ -84,7 +84,7 @@ type Peer struct { txBroadcast chan []common.Hash // Channel used to queue transaction propagation requests txAnnounce chan []common.Hash // Channel used to queue transaction announcement requests - reqDispatch chan *request // Dispatch channel to send requests and track then until fulfilment + reqDispatch chan *request // Dispatch channel to send requests and track then until fulfillment reqCancel chan *cancel // Dispatch channel to cancel pending requests and untrack them resDispatch chan *response // Dispatch channel to fulfil pending requests and untrack them diff --git a/eth/tracers/api_bor.go b/eth/tracers/api_bor.go index 565148c384..3172784b15 100644 --- a/eth/tracers/api_bor.go +++ b/eth/tracers/api_bor.go @@ -140,7 +140,7 @@ type TraceBlockRequest struct { Config *TraceConfig } -// If you use context as first parameter this function gets exposed automaticall on rpc endpoint +// If you use context as first parameter this function gets exposed automatically on rpc endpoint func (api *API) TraceBorBlock(req *TraceBlockRequest) (*BlockTraceResult, error) { ctx := context.Background() diff --git a/eth/tracers/js/internal/tracers/call_tracer_legacy.js b/eth/tracers/js/internal/tracers/call_tracer_legacy.js index 451a644b91..0760bb1e3f 100644 --- a/eth/tracers/js/internal/tracers/call_tracer_legacy.js +++ b/eth/tracers/js/internal/tracers/call_tracer_legacy.js @@ -219,7 +219,7 @@ return this.finalize(result); }, - // finalize recreates a call object using the final desired field oder for json + // finalize recreates a call object using the final desired field order for json // serialization. This is a nicety feature to pass meaningfully ordered results // to users who don't interpret it, just display it. finalize: function(call) { diff --git a/eth/tracers/tracers_test.go b/eth/tracers/tracers_test.go index 5990b40e8b..4d661c15be 100644 --- a/eth/tracers/tracers_test.go +++ b/eth/tracers/tracers_test.go @@ -133,9 +133,9 @@ func TestMemCopying(t *testing.T) { {0, 100, 0, "", 0}, // No need to pad (0 size) {100, 50, 100, "", 100}, // Should pad 100-150 {100, 50, 5, "", 5}, // Wanted range fully within memory - {100, -50, 0, "offset or size must not be negative", 0}, // Errror - {0, 1, 1024*1024 + 1, "reached limit for padding memory slice: 1048578", 0}, // Errror - {10, 0, 1024*1024 + 100, "reached limit for padding memory slice: 1048666", 0}, // Errror + {100, -50, 0, "offset or size must not be negative", 0}, // Error + {0, 1, 1024*1024 + 1, "reached limit for padding memory slice: 1048578", 0}, // Error + {10, 0, 1024*1024 + 100, "reached limit for padding memory slice: 1048666", 0}, // Error } { mem := vm.NewMemory() diff --git a/ethclient/gethclient/gethclient_test.go b/ethclient/gethclient/gethclient_test.go index d06ef8e055..9b459c7503 100644 --- a/ethclient/gethclient/gethclient_test.go +++ b/ethclient/gethclient/gethclient_test.go @@ -452,7 +452,7 @@ func TestOverrideAccountMarshal(t *testing.T) { om := map[common.Address]OverrideAccount{ {0x11}: { - // Zero-valued nonce is not overriddden, but simply dropped by the encoder. + // Zero-valued nonce is not overridden, but simply dropped by the encoder. Nonce: 0, }, {0xaa}: { diff --git a/graphql/graphql.go b/graphql/graphql.go index 7aa427b458..f03644eeb4 100644 --- a/graphql/graphql.go +++ b/graphql/graphql.go @@ -1121,7 +1121,7 @@ func (c *CallResult) Status() hexutil.Uint64 { func (b *Block) Call(ctx context.Context, args struct { Data ethapi.TransactionArgs }) (*CallResult, error) { - result, err := ethapi.DoCall(ctx, b.r.backend, args.Data, *b.numberOrHash, nil, nil, b.r.backend.RPCEVMTimeout(), b.r.backend.RPCGasCap()) + result, err := ethapi.DoCall(ctx, b.r.backend, args.Data, *b.numberOrHash, nil, nil, nil, b.r.backend.RPCEVMTimeout(), b.r.backend.RPCGasCap()) if err != nil { return nil, err } @@ -1184,7 +1184,7 @@ func (p *Pending) Call(ctx context.Context, args struct { Data ethapi.TransactionArgs }) (*CallResult, error) { pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber) - result, err := ethapi.DoCall(ctx, p.r.backend, args.Data, pendingBlockNr, nil, nil, p.r.backend.RPCEVMTimeout(), p.r.backend.RPCGasCap()) + result, err := ethapi.DoCall(ctx, p.r.backend, args.Data, pendingBlockNr, nil, nil, nil, p.r.backend.RPCEVMTimeout(), p.r.backend.RPCGasCap()) if err != nil { return nil, err } diff --git a/internal/cli/flagset/flagset.go b/internal/cli/flagset/flagset.go index 85a846a40b..6443d4f8b7 100644 --- a/internal/cli/flagset/flagset.go +++ b/internal/cli/flagset/flagset.go @@ -368,7 +368,7 @@ func (i *SliceStringFlag) String() string { } func (i *SliceStringFlag) Set(value string) error { - // overwritting insted of appending + // overwriting instead of appending *i.Value = SplitAndTrim(value) return nil } diff --git a/internal/cli/server/chains/mainnet.go b/internal/cli/server/chains/mainnet.go index b9efd9a4e2..5548f8edba 100644 --- a/internal/cli/server/chains/mainnet.go +++ b/internal/cli/server/chains/mainnet.go @@ -29,10 +29,9 @@ var mainnetBor = &Chain{ LondonBlock: big.NewInt(23850000), ShanghaiBlock: big.NewInt(50523000), Bor: ¶ms.BorConfig{ - JaipurBlock: big.NewInt(23850000), - DelhiBlock: big.NewInt(38189056), - ParallelUniverseBlock: big.NewInt(0), - IndoreBlock: big.NewInt(44934656), + JaipurBlock: big.NewInt(23850000), + DelhiBlock: big.NewInt(38189056), + IndoreBlock: big.NewInt(44934656), StateSyncConfirmationDelay: map[string]uint64{ "44934656": 128, }, diff --git a/internal/cli/server/chains/mumbai.go b/internal/cli/server/chains/mumbai.go index 45f36fbe89..7fe25554c5 100644 --- a/internal/cli/server/chains/mumbai.go +++ b/internal/cli/server/chains/mumbai.go @@ -29,10 +29,9 @@ var mumbaiTestnet = &Chain{ LondonBlock: big.NewInt(22640000), ShanghaiBlock: big.NewInt(41874000), Bor: ¶ms.BorConfig{ - JaipurBlock: big.NewInt(22770000), - DelhiBlock: big.NewInt(29638656), - ParallelUniverseBlock: big.NewInt(0), - IndoreBlock: big.NewInt(37075456), + JaipurBlock: big.NewInt(22770000), + DelhiBlock: big.NewInt(29638656), + IndoreBlock: big.NewInt(37075456), StateSyncConfirmationDelay: map[string]uint64{ "37075456": 128, }, diff --git a/internal/cli/server/chains/test_files/chain_legacy_test.json b/internal/cli/server/chains/test_files/chain_legacy_test.json index a64fbf3e23..c3e9b3c7bf 100644 --- a/internal/cli/server/chains/test_files/chain_legacy_test.json +++ b/internal/cli/server/chains/test_files/chain_legacy_test.json @@ -57,7 +57,6 @@ }, "jaipurBlock": 22770000, "delhiBlock": 29638656, - "parallelUniverseBlock": 0, "indoreBlock": 37075456, "stateSyncConfirmationDelay": { "37075456": 128 diff --git a/internal/cli/server/chains/test_files/chain_test.json b/internal/cli/server/chains/test_files/chain_test.json index ba207bf770..8555833321 100644 --- a/internal/cli/server/chains/test_files/chain_test.json +++ b/internal/cli/server/chains/test_files/chain_test.json @@ -59,7 +59,6 @@ }, "jaipurBlock":22770000, "delhiBlock": 29638656, - "parallelUniverseBlock": 0, "indoreBlock": 37075456, "stateSyncConfirmationDelay": { "37075456": 128 diff --git a/internal/cli/server/command.go b/internal/cli/server/command.go index 817c09b670..5170acab77 100644 --- a/internal/cli/server/command.go +++ b/internal/cli/server/command.go @@ -94,7 +94,7 @@ func (c *Command) extractFlags(args []string) error { log.Warn("Config set via config file will be overridden by cli flags") - // Initialse a flagset based on the config created above + // Initialise a flagset based on the config created above flags := c.Flags(cfg) // Check for explicit cli args diff --git a/internal/cli/server/config_legacy_test.go b/internal/cli/server/config_legacy_test.go index e9957c3353..aa6cffc470 100644 --- a/internal/cli/server/config_legacy_test.go +++ b/internal/cli/server/config_legacy_test.go @@ -42,22 +42,3 @@ func TestConfigLegacy(t *testing.T) { readFile("./testdata/test.toml") }) } - -func TestDefaultConfigLegacy(t *testing.T) { - readFile := func(path string) { - expectedConfig, err := readLegacyConfig(path) - assert.NoError(t, err) - - testConfig := DefaultConfig() - - testConfig.Identity = "Polygon-Devs" - testConfig.DataDir = "/var/lib/bor" - - assert.Equal(t, expectedConfig, testConfig) - } - - // read file in hcl format - t.Run("toml", func(t *testing.T) { - readFile("./testdata/default.toml") - }) -} diff --git a/internal/cli/server/testdata/default.toml b/internal/cli/server/testdata/default.toml deleted file mode 100644 index 3a6c2f0cb5..0000000000 --- a/internal/cli/server/testdata/default.toml +++ /dev/null @@ -1,193 +0,0 @@ -chain = "mainnet" -identity = "Polygon-Devs" -verbosity = 3 -log-level = "" -vmdebug = false -datadir = "/var/lib/bor" -ancient = "" -"db.engine" = "leveldb" -keystore = "" -"rpc.batchlimit" = 100 -"rpc.returndatalimit" = 100000 -syncmode = "full" -gcmode = "full" -snapshot = true -"bor.logs" = false -ethstats = "" -devfakeauthor = false - -["eth.requiredblocks"] - -[log] - vmodule = "" - json = false - backtrace = "" - debug = false - -[p2p] - maxpeers = 50 - maxpendpeers = 50 - bind = "0.0.0.0" - port = 30303 - nodiscover = false - nat = "any" - netrestrict = "" - nodekey = "" - nodekeyhex = "" - txarrivalwait = "500ms" - [p2p.discovery] - v4disc = true - v5disc = false - bootnodes = [] - bootnodesv4 = [] - bootnodesv5 = [] - static-nodes = [] - trusted-nodes = [] - dns = [] - -[heimdall] - url = "http://localhost:1317" - "bor.without" = false - grpc-address = "" - "bor.runheimdall" = false - "bor.runheimdallargs" = "" - "bor.useheimdallapp" = false - -[txpool] - locals = [] - nolocals = false - journal = "transactions.rlp" - rejournal = "1h0m0s" - pricelimit = 1 - pricebump = 10 - accountslots = 16 - globalslots = 32768 - accountqueue = 16 - globalqueue = 32768 - lifetime = "3h0m0s" - -[miner] - mine = false - etherbase = "" - extradata = "" - gaslimit = 30000000 - gasprice = "1000000000" - recommit = "2m5s" - commitinterrupt = true - -[jsonrpc] - ipcdisable = false - ipcpath = "" - gascap = 50000000 - evmtimeout = "5s" - txfeecap = 1.0 - allow-unprotected-txs = false - enabledeprecatedpersonal = false - [jsonrpc.http] - enabled = false - port = 8545 - prefix = "" - host = "localhost" - api = ["eth", "net", "web3", "txpool", "bor"] - vhosts = ["localhost"] - corsdomain = ["localhost"] - ep-size = 40 - ep-requesttimeout = "0s" - [jsonrpc.ws] - enabled = false - port = 8546 - prefix = "" - host = "localhost" - api = ["net", "web3"] - origins = ["localhost"] - ep-size = 40 - ep-requesttimeout = "0s" - [jsonrpc.graphql] - enabled = false - port = 0 - prefix = "" - host = "" - vhosts = ["localhost"] - corsdomain = ["localhost"] - ep-size = 0 - ep-requesttimeout = "" - [jsonrpc.auth] - jwtsecret = "" - addr = "localhost" - port = 8551 - vhosts = ["localhost"] - [jsonrpc.timeouts] - read = "10s" - write = "30s" - idle = "2m0s" - -[gpo] - blocks = 20 - percentile = 60 - maxheaderhistory = 1024 - maxblockhistory = 1024 - maxprice = "500000000000" - ignoreprice = "2" - -[telemetry] - metrics = false - expensive = false - prometheus-addr = "127.0.0.1:7071" - opencollector-endpoint = "" - [telemetry.influx] - influxdb = false - endpoint = "" - database = "" - username = "" - password = "" - influxdbv2 = false - token = "" - bucket = "" - organization = "" - [telemetry.influx.tags] - -[cache] - cache = 1024 - gc = 25 - snapshot = 10 - database = 50 - trie = 15 - noprefetch = false - preimages = false - txlookuplimit = 2350000 - triesinmemory = 128 - blocklogs = 32 - timeout = "1h0m0s" - fdlimit = 0 - -[leveldb] - compactiontablesize = 2 - compactiontablesizemultiplier = 1.0 - compactiontotalsize = 10 - compactiontotalsizemultiplier = 10.0 - -[accounts] - unlock = [] - password = "" - allow-insecure-unlock = false - lightkdf = false - disable-bor-wallet = true - -[grpc] - addr = ":3131" - -[developer] - dev = false - period = 0 - gaslimit = 11500000 - -[parallelevm] - enable = true - procs = 8 - -[pprof] - pprof = false - port = 6060 - addr = "127.0.0.1" - memprofilerate = 524288 - blockprofilerate = 0 diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 25e05ac17d..25c6ab97f6 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -702,8 +702,12 @@ func (s *BlockChainAPI) GetTransactionReceiptsByBlock(ctx context.Context, block for idx, receipt := range receipts { tx := txs[idx] - // Derive the sender. - signer := types.MakeSigner(s.b.ChainConfig(), block.Number(), block.Time()) + var signer types.Signer = types.FrontierSigner{} + + if tx.Protected() { + signer = types.NewEIP155Signer(tx.ChainId()) + } + from, _ := types.Sender(signer, tx) fields := map[string]interface{}{ @@ -719,11 +723,6 @@ func (s *BlockChainAPI) GetTransactionReceiptsByBlock(ctx context.Context, block "logs": receipt.Logs, "logsBloom": receipt.Bloom, "type": hexutil.Uint(tx.Type()), - "effectiveGasPrice": (*hexutil.Big)(receipt.EffectiveGasPrice), - } - - if receipt.EffectiveGasPrice == nil { - fields["effectiveGasPrice"] = new(hexutil.Big) } // Assign receipt status or post state. @@ -734,7 +733,7 @@ func (s *BlockChainAPI) GetTransactionReceiptsByBlock(ctx context.Context, block } if receipt.Logs == nil { - fields["logs"] = []*types.Log{} + fields["logs"] = [][]*types.Log{} } if borReceipt != nil && idx == len(receipts)-1 { @@ -1265,12 +1264,31 @@ func doCallWithState(ctx context.Context, b Backend, args TransactionArgs, heade return result, nil } -func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, blockOverrides *BlockOverrides, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) { +func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, state *state.StateDB, overrides *StateOverride, blockOverrides *BlockOverrides, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) { defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now()) - state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) - if state == nil || err != nil { - return nil, err + var ( + header *types.Header + err error + ) + + // BOR: This is used by bor consensus to fetch data from genesis contracts for state-sync + // Fetch the state and header from blockNumberOrHash if it's coming from normal eth_call path. + if state == nil { + state, header, err = b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) + if state == nil || err != nil { + return nil, err + } + } else { + // Fetch the header from the given blockNumberOrHash. Note that this path is only taken + // when we're doing a call from bor consensus to fetch data from genesis contracts. It's + // necessary to fetch header using header hash as we might be experiencing a reorg and there + // can be multiple headers with same number. + header, err = b.HeaderByHash(ctx, *blockNrOrHash.BlockHash) + if header == nil || err != nil { + log.Warn("Error fetching header on CallWithState", "err", err) + return nil, err + } } return doCall(ctx, b, args, state, header, overrides, blockOverrides, timeout, globalGasCap) @@ -1328,7 +1346,7 @@ func (s *BlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrO // Note, this function doesn't make and changes in the state/blockchain and is // useful to execute and retrieve values. func (s *BlockChainAPI) CallWithState(ctx context.Context, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, state *state.StateDB, overrides *StateOverride, blockOverrides *BlockOverrides) (hexutil.Bytes, error) { - result, err := DoCall(ctx, s.b, args, blockNrOrHash, overrides, blockOverrides, s.b.RPCEVMTimeout(), s.b.RPCGasCap()) + result, err := DoCall(ctx, s.b, args, blockNrOrHash, state, overrides, blockOverrides, s.b.RPCEVMTimeout(), s.b.RPCGasCap()) if err != nil { return nil, err } diff --git a/internal/ethapi/api_test.go b/internal/ethapi/api_test.go index 6fe9a54130..152a24ddef 100644 --- a/internal/ethapi/api_test.go +++ b/internal/ethapi/api_test.go @@ -2146,251 +2146,3 @@ func TestRPCGetTransactionReceipt(t *testing.T) { require.JSONEqf(t, want, have, "test %d: json not match, want: %s, have: %s", i, want, have) } } - -func TestRPCGetTransactionReceiptsByBlock(t *testing.T) { - t.Parallel() - - // Initialize test accounts - var ( - acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a") - acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee") - acc1Addr = crypto.PubkeyToAddress(acc1Key.PublicKey) - acc2Addr = crypto.PubkeyToAddress(acc2Key.PublicKey) - contract = common.HexToAddress("0000000000000000000000000000000000031ec7") - genesis = &core.Genesis{ - Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ - acc1Addr: {Balance: big.NewInt(params.Ether)}, - acc2Addr: {Balance: big.NewInt(params.Ether)}, - contract: {Balance: big.NewInt(params.Ether), Code: common.FromHex("0x608060405234801561001057600080fd5b506004361061002b5760003560e01c8063a9059cbb14610030575b600080fd5b61004a6004803603810190610045919061016a565b610060565b60405161005791906101c5565b60405180910390f35b60008273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040516100bf91906101ef565b60405180910390a36001905092915050565b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000610101826100d6565b9050919050565b610111816100f6565b811461011c57600080fd5b50565b60008135905061012e81610108565b92915050565b6000819050919050565b61014781610134565b811461015257600080fd5b50565b6000813590506101648161013e565b92915050565b60008060408385031215610181576101806100d1565b5b600061018f8582860161011f565b92505060206101a085828601610155565b9150509250929050565b60008115159050919050565b6101bf816101aa565b82525050565b60006020820190506101da60008301846101b6565b92915050565b6101e981610134565b82525050565b600060208201905061020460008301846101e0565b9291505056fea2646970667358221220b469033f4b77b9565ee84e0a2f04d496b18160d26034d54f9487e57788fd36d564736f6c63430008120033")}, - }, - } - genTxs = 5 - genBlocks = 1 - signer = types.LatestSignerForChainID(params.TestChainConfig.ChainID) - txHashes = make([]common.Hash, 0, genTxs) - ) - - backend := newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) { - switch i { - case 0: - // transfer 1000wei - tx1, _ := types.SignTx(types.NewTx(&types.LegacyTx{Nonce: uint64(0), To: &acc2Addr, Value: big.NewInt(1000), Gas: params.TxGas, GasPrice: b.BaseFee(), Data: nil}), types.HomesteadSigner{}, acc1Key) - b.AddTx(tx1) - txHashes = append(txHashes, tx1.Hash()) - - // create contract - tx2, _ := types.SignTx(types.NewTx(&types.LegacyTx{Nonce: uint64(1), To: nil, Gas: 53100, GasPrice: b.BaseFee(), Data: common.FromHex("0x60806040")}), signer, acc1Key) - b.AddTx(tx2) - txHashes = append(txHashes, tx2.Hash()) - - // with logs - // transfer(address to, uint256 value) - data3 := fmt.Sprintf("0xa9059cbb%s%s", common.HexToHash(common.BigToAddress(big.NewInt(int64(i + 1))).Hex()).String()[2:], common.BytesToHash([]byte{byte(i + 11)}).String()[2:]) - tx3, _ := types.SignTx(types.NewTx(&types.LegacyTx{Nonce: uint64(2), To: &contract, Gas: 60000, GasPrice: b.BaseFee(), Data: common.FromHex(data3)}), signer, acc1Key) - b.AddTx(tx3) - txHashes = append(txHashes, tx3.Hash()) - - // dynamic fee with logs - // transfer(address to, uint256 value) - data4 := fmt.Sprintf("0xa9059cbb%s%s", common.HexToHash(common.BigToAddress(big.NewInt(int64(i + 1))).Hex()).String()[2:], common.BytesToHash([]byte{byte(i + 11)}).String()[2:]) - fee := big.NewInt(500) - fee.Add(fee, b.BaseFee()) - tx4, _ := types.SignTx(types.NewTx(&types.DynamicFeeTx{Nonce: uint64(3), To: &contract, Gas: 60000, Value: big.NewInt(1), GasTipCap: big.NewInt(500), GasFeeCap: fee, Data: common.FromHex(data4)}), signer, acc1Key) - b.AddTx(tx4) - txHashes = append(txHashes, tx4.Hash()) - - // access list with contract create - accessList := types.AccessList{{ - Address: contract, - StorageKeys: []common.Hash{{0}}, - }} - tx5, _ := types.SignTx(types.NewTx(&types.AccessListTx{Nonce: uint64(4), To: nil, Gas: 58100, GasPrice: b.BaseFee(), Data: common.FromHex("0x60806040"), AccessList: accessList}), signer, acc1Key) - b.AddTx(tx5) - txHashes = append(txHashes, tx5.Hash()) - } - }) - - api := NewBlockChainAPI(backend) - blockHashes := make([]common.Hash, genBlocks+1) - ctx := context.Background() - for i := 0; i <= genBlocks; i++ { - header, err := backend.HeaderByNumber(ctx, rpc.BlockNumber(i)) - if err != nil { - t.Errorf("failed to get block: %d err: %v", i, err) - } - blockHashes[i] = header.Hash() - } - blockNrOrHash := rpc.BlockNumberOrHashWithHash(blockHashes[1], true) - - var testSuite = []struct { - txHash common.Hash - want string - }{ - // 0. normal success - { - txHash: txHashes[0], - want: `{ - "blockHash": "0x1728b788dfe51e507d25f14f01414b5a17f807953c13833811d2afae1982b53b", - "blockNumber": "0x1", - "contractAddress": null, - "cumulativeGasUsed": "0x5208", - "effectiveGasPrice": "0x342770c0", - "from": "0x703c4b2bd70c169f5717101caee543299fc946c7", - "gasUsed": "0x5208", - "logs": [ - { - "address": "0x0000000000000000000000000000000000001010", - "topics": [ - "0xe6497e3ee548a3372136af2fcb0696db31fc6cf20260707645068bd3fe97f3c4", - "0x0000000000000000000000000000000000000000000000000000000000001010", - "0x000000000000000000000000703c4b2bd70c169f5717101caee543299fc946c7", - "0x0000000000000000000000000d3ab14bbad3d99f4203bd7a11acb94882050e7e" - ], - "data": "0x00000000000000000000000000000000000000000000000000000000000003e80000000000000000000000000000000000000000000000000de0a5fd640afa000000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000de0a5fd640af6180000000000000000000000000000000000000000000000000de0b6b3a76403e8", - "blockNumber": "0x1", - "transactionHash": "0x644a31c354391520d00e95b9affbbb010fc79ac268144ab8e28207f4cf51097e", - "transactionIndex": "0x0", - "blockHash": "0x1728b788dfe51e507d25f14f01414b5a17f807953c13833811d2afae1982b53b", - "logIndex": "0x0", - "removed": false - } - ], - "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000808000000000000000000000000000000000000000000000000000000000800000000000000000000100000020000000000000000000000000000000000802000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000800000000000000000000000800000108000000000000000000000000000000000000000000000000020000000000000000000100000", - "status": "0x1", - "to": "0x0d3ab14bbad3d99f4203bd7a11acb94882050e7e", - "transactionHash": "0x644a31c354391520d00e95b9affbbb010fc79ac268144ab8e28207f4cf51097e", - "transactionIndex": "0x0", - "type": "0x0" - }`, - }, - // 1. create contract - { - txHash: txHashes[1], - want: `{ - "blockHash": "0x1728b788dfe51e507d25f14f01414b5a17f807953c13833811d2afae1982b53b", - "blockNumber": "0x1", - "contractAddress": "0xae9bea628c4ce503dcfd7e305cab4e29e7476592", - "cumulativeGasUsed": "0x12156", - "effectiveGasPrice": "0x342770c0", - "from": "0x703c4b2bd70c169f5717101caee543299fc946c7", - "gasUsed": "0xcf4e", - "logs": [], - "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "status": "0x1", - "to": null, - "transactionHash": "0x705a7fca1d214002ee90d4e1c651b53e3506e6d5e3a539e9a7f7bf05b49add91", - "transactionIndex": "0x1", - "type": "0x0" - }`, - }, - // 2. with logs success - { - txHash: txHashes[2], - want: `{ - "blockHash": "0x1728b788dfe51e507d25f14f01414b5a17f807953c13833811d2afae1982b53b", - "blockNumber": "0x1", - "contractAddress": null, - "cumulativeGasUsed": "0x17f7e", - "effectiveGasPrice": "0x342770c0", - "from": "0x703c4b2bd70c169f5717101caee543299fc946c7", - "gasUsed": "0x5e28", - "logs": [ - { - "address": "0x0000000000000000000000000000000000031ec7", - "topics": [ - "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", - "0x000000000000000000000000703c4b2bd70c169f5717101caee543299fc946c7", - "0x0000000000000000000000000000000000000000000000000000000000000001" - ], - "data": "0x000000000000000000000000000000000000000000000000000000000000000b", - "blockNumber": "0x1", - "transactionHash": "0xa228af0975b99799bd28331085a6966aba2fb5814a8d89aabc342462aa40429a", - "transactionIndex": "0x2", - "blockHash": "0x1728b788dfe51e507d25f14f01414b5a17f807953c13833811d2afae1982b53b", - "logIndex": "0x1", - "removed": false - } - ], - "logsBloom": "0x00000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000800000000000000008000000000000000000040000000000000020000000080000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000800000000000000000000000000000000000000040000000000000000000000000000000000000000020000000000000000000000000", - "status": "0x1", - "to": "0x0000000000000000000000000000000000031ec7", - "transactionHash": "0xa228af0975b99799bd28331085a6966aba2fb5814a8d89aabc342462aa40429a", - "transactionIndex": "0x2", - "type": "0x0" - }`, - }, - // 3. dynamic tx with logs success - { - txHash: txHashes[3], - want: `{ - "blockHash": "0x1728b788dfe51e507d25f14f01414b5a17f807953c13833811d2afae1982b53b", - "blockNumber": "0x1", - "contractAddress": null, - "cumulativeGasUsed": "0x1d30b", - "effectiveGasPrice": "0x342772b4", - "from": "0x703c4b2bd70c169f5717101caee543299fc946c7", - "gasUsed": "0x538d", - "logs": [ - { - "address": "0x0000000000000000000000000000000000001010", - "topics": [ - "0x4dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63", - "0x0000000000000000000000000000000000000000000000000000000000001010", - "0x000000000000000000000000703c4b2bd70c169f5717101caee543299fc946c7", - "0x0000000000000000000000000000000000000000000000000000000000000000" - ], - "data": "0x0000000000000000000000000000000000000000000000000000000000a32f640000000000000000000000000000000000000000000000000de06892fa4b3d9800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000de06892f9a80e340000000000000000000000000000000000000000000000000000000000a32f64", - "blockNumber": "0x1", - "transactionHash": "0xc2cc458a65bc96f642d4a2063cce162b0da642613d801271bdbc4aa7e775f3ed", - "transactionIndex": "0x3", - "blockHash": "0x1728b788dfe51e507d25f14f01414b5a17f807953c13833811d2afae1982b53b", - "logIndex": "0x2", - "removed": false - } - ], - "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000800000000000000000000100000020000000000000020000000000000000000800000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000004000000000000000000001800000000000000000000000000000100000000020000000000000000000000000000000000000000020000000000000000000100000", - "status": "0x0", - "to": "0x0000000000000000000000000000000000031ec7", - "transactionHash": "0xc2cc458a65bc96f642d4a2063cce162b0da642613d801271bdbc4aa7e775f3ed", - "transactionIndex": "0x3", - "type": "0x2" - }`, - }, - // 4. access list tx with create contract - { - txHash: txHashes[4], - want: `{ - "blockHash": "0x1728b788dfe51e507d25f14f01414b5a17f807953c13833811d2afae1982b53b", - "blockNumber": "0x1", - "contractAddress": "0xfdaa97661a584d977b4d3abb5370766ff5b86a18", - "cumulativeGasUsed": "0x2b325", - "effectiveGasPrice": "0x342770c0", - "from": "0x703c4b2bd70c169f5717101caee543299fc946c7", - "gasUsed": "0xe01a", - "logs": [], - "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "status": "0x1", - "to": null, - "transactionHash": "0x1e1161cf3fd01a02fc9c5ee66fc45a4805b3828bf41edd54213c20d97fc12b1d", - "transactionIndex": "0x4", - "type": "0x1" - }`, - }, - } - - receipts, err := api.GetTransactionReceiptsByBlock(context.Background(), blockNrOrHash) - if err != nil { - t.Fatal("api error") - } - - for i, tt := range testSuite { - data, err := json.Marshal(receipts[i]) - if err != nil { - t.Errorf("test %d: json marshal error", i) - continue - } - want, have := tt.want, string(data) - require.JSONEqf(t, want, have, "test %d: json not match, want: %s, have: %s", i, want, have) - } -} diff --git a/internal/flags/helpers.go b/internal/flags/helpers.go index 21689840f0..10765f932b 100644 --- a/internal/flags/helpers.go +++ b/internal/flags/helpers.go @@ -113,7 +113,7 @@ func doMigrateFlags(ctx *cli.Context) { for _, parent := range ctx.Lineage()[1:] { if parent.IsSet(name) { // When iterating across the lineage, we will be served both - // the 'canon' and alias formats of all commmands. In most cases, + // the 'canon' and alias formats of all commands. In most cases, // it's fine to set it in the ctx multiple times (one for each // name), however, the Slice-flags are not fine. // The slice-flags accumulate, so if we set it once as diff --git a/internal/jsre/deps/web3.js b/internal/jsre/deps/web3.js index a8ca37cec5..70bd4b1508 100644 --- a/internal/jsre/deps/web3.js +++ b/internal/jsre/deps/web3.js @@ -2031,7 +2031,7 @@ var fromAscii = function(str) { * * @method transformToFullName * @param {Object} json-abi - * @return {String} full fnction/event name + * @return {String} full function/event name */ var transformToFullName = function (json) { if (json.name.indexOf('(') !== -1) { @@ -2089,7 +2089,7 @@ var fromDecimal = function (value) { /** * Auto converts any given value into it's hex representation. * - * And even stringifys objects before. + * And even stringifies objects before. * * @method toHex * @param {String|Number|BigNumber|Object} @@ -2361,7 +2361,7 @@ var isFunction = function (object) { }; /** - * Returns true if object is Objet, otherwise false + * Returns true if object is Object, otherwise false * * @method isObject * @param {Object} @@ -2757,7 +2757,7 @@ var Batch = function (web3) { * Should be called to add create new request to batch request * * @method add - * @param {Object} jsonrpc requet object + * @param {Object} jsonrpc request object */ Batch.prototype.add = function (request) { this.requests.push(request); @@ -4557,7 +4557,7 @@ Iban.createIndirect = function (options) { }; /** - * Thos method should be used to check if given string is valid iban object + * This method should be used to check if given string is valid iban object * * @method isValid * @param {String} iban string @@ -6721,7 +6721,7 @@ var exchangeAbi = require('../contracts/SmartExchange.json'); * @method transfer * @param {String} from * @param {String} to iban - * @param {Value} value to be tranfered + * @param {Value} value to be transferred * @param {Function} callback, callback */ var transfer = function (eth, from, to, value, callback) { @@ -6751,7 +6751,7 @@ var transfer = function (eth, from, to, value, callback) { * @method transferToAddress * @param {String} from * @param {String} to - * @param {Value} value to be tranfered + * @param {Value} value to be transferred * @param {Function} callback, callback */ var transferToAddress = function (eth, from, to, value, callback) { @@ -7105,7 +7105,7 @@ module.exports = transfer; /** * Initializes a newly created cipher. * - * @param {number} xformMode Either the encryption or decryption transormation mode constant. + * @param {number} xformMode Either the encryption or decryption transformation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * @@ -9459,7 +9459,7 @@ module.exports = transfer; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; - // Working varialbes + // Working variables var a = H[0]; var b = H[1]; var c = H[2]; diff --git a/les/utils/timeutils_test.go b/les/utils/timeutils_test.go index b219d0439d..165f37352e 100644 --- a/les/utils/timeutils_test.go +++ b/les/utils/timeutils_test.go @@ -42,6 +42,6 @@ func TestUpdateTimer(t *testing.T) { } timer = NewUpdateTimer(sim, 0) if updated := timer.Update(func(diff time.Duration) bool { return true }); !updated { - t.Fatalf("Doesn't update the clock without threshold limitaion") + t.Fatalf("Doesn't update the clock without threshold limitation") } } diff --git a/log/doc.go b/log/doc.go index d2e15140e4..f533364d0f 100644 --- a/log/doc.go +++ b/log/doc.go @@ -195,7 +195,7 @@ on log level. # Error Handling -Becasuse log15 allows you to step around the type system, there are a few ways you can specify +Because log15 allows you to step around the type system, there are a few ways you can specify invalid arguments to the logging functions. You could, for example, wrap something that is not a zero-argument function with log.Lazy or pass a context key that is not a string. Since logging libraries are typically the mechanism by which errors are reported, it would be onerous for the logging functions diff --git a/log/format.go b/log/format.go index 6a03013b81..8d72d8ce09 100644 --- a/log/format.go +++ b/log/format.go @@ -39,7 +39,7 @@ func PrintOrigins(print bool) { // should append the log locations too when printing entries. var locationEnabled atomic.Bool -// locationLength is the maxmimum path length encountered, which all logs are +// locationLength is the maximum path length encountered, which all logs are // padded to to aid in alignment. var locationLength atomic.Uint32 diff --git a/miner/payload_building_test.go b/miner/payload_building_test.go index 02f1008f4c..c2d9262de2 100644 --- a/miner/payload_building_test.go +++ b/miner/payload_building_test.go @@ -56,23 +56,23 @@ func TestBuildPayload(t *testing.T) { verify := func(outer *engine.ExecutionPayloadEnvelope, txs int) { payload := outer.ExecutionPayload if payload.ParentHash != b.chain.CurrentBlock().Hash() { - t.Fatal("Unexpect parent hash") + t.Fatal("Unexpected parent hash") } if payload.Random != (common.Hash{}) { - t.Fatal("Unexpect random value") + t.Fatal("Unexpected random value") } if payload.Timestamp != timestamp { - t.Fatal("Unexpect timestamp") + t.Fatal("Unexpected timestamp") } if payload.FeeRecipient != recipient { - t.Fatal("Unexpect fee recipient") + t.Fatal("Unexpected fee recipient") } if len(payload.Transactions) != txs { - t.Fatal("Unexpect transaction set") + t.Fatal("Unexpected transaction set") } } empty := payload.ResolveEmpty() diff --git a/miner/worker.go b/miner/worker.go index e9cd1bebd7..7842cd57d3 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -109,17 +109,22 @@ type environment struct { header *types.Header txs []*types.Transaction receipts []*types.Receipt + + depsMVFullWriteList [][]blockstm.WriteDescriptor + mvReadMapList []map[blockstm.Key]blockstm.ReadDescriptor } // copy creates a deep copy of environment. func (env *environment) copy() *environment { cpy := &environment{ - signer: env.signer, - state: env.state.Copy(), - tcount: env.tcount, - coinbase: env.coinbase, - header: types.CopyHeader(env.header), - receipts: copyReceipts(env.receipts), + signer: env.signer, + state: env.state.Copy(), + tcount: env.tcount, + coinbase: env.coinbase, + header: types.CopyHeader(env.header), + receipts: copyReceipts(env.receipts), + depsMVFullWriteList: env.depsMVFullWriteList, + mvReadMapList: env.mvReadMapList, } if env.gasPool != nil { @@ -854,6 +859,9 @@ func (w *worker) makeEnv(parent *types.Header, header *types.Header, coinbase co // Keep track of transactions which return errors so they can be removed env.tcount = 0 + env.depsMVFullWriteList = [][]blockstm.WriteDescriptor{} + env.mvReadMapList = []map[blockstm.Key]blockstm.ReadDescriptor{} + return env, nil } @@ -903,36 +911,20 @@ func (w *worker) commitTransactions(env *environment, txs *transactionsByPriceAn var coalescedLogs []*types.Log - var depsMVReadList [][]blockstm.ReadDescriptor - - var depsMVFullWriteList [][]blockstm.WriteDescriptor - - var mvReadMapList []map[blockstm.Key]blockstm.ReadDescriptor - var deps map[int]map[int]bool chDeps := make(chan blockstm.TxDep) - var count int - var depsWg sync.WaitGroup - EnableMVHashMap := w.chainConfig.Bor.IsParallelUniverse(env.header.Number) + EnableMVHashMap := w.chainConfig.IsCancun(env.header.Number) // create and add empty mvHashMap in statedb if EnableMVHashMap { - depsMVReadList = [][]blockstm.ReadDescriptor{} - - depsMVFullWriteList = [][]blockstm.WriteDescriptor{} - - mvReadMapList = []map[blockstm.Key]blockstm.ReadDescriptor{} - deps = map[int]map[int]bool{} chDeps = make(chan blockstm.TxDep) - count = 0 - depsWg.Add(1) go func(chDeps chan blockstm.TxDep) { @@ -1064,18 +1056,20 @@ mainloop: env.tcount++ if EnableMVHashMap { - depsMVReadList = append(depsMVReadList, env.state.MVReadList()) - depsMVFullWriteList = append(depsMVFullWriteList, env.state.MVFullWriteList()) - mvReadMapList = append(mvReadMapList, env.state.MVReadMap()) + env.depsMVFullWriteList = append(env.depsMVFullWriteList, env.state.MVFullWriteList()) + env.mvReadMapList = append(env.mvReadMapList, env.state.MVReadMap()) + + if env.tcount > len(env.depsMVFullWriteList) { + log.Warn("blockstm - env.tcount > len(env.depsMVFullWriteList)", "env.tcount", env.tcount, "len(depsMVFullWriteList)", len(env.depsMVFullWriteList)) + } temp := blockstm.TxDep{ Index: env.tcount - 1, - ReadList: depsMVReadList[count], - FullWriteList: depsMVFullWriteList, + ReadList: env.state.MVReadList(), + FullWriteList: env.depsMVFullWriteList, } chDeps <- temp - count++ } txs.Shift() @@ -1107,8 +1101,8 @@ mainloop: tempVanity := env.header.Extra[:types.ExtraVanityLength] tempSeal := env.header.Extra[len(env.header.Extra)-types.ExtraSealLength:] - if len(mvReadMapList) > 0 { - tempDeps := make([][]uint64, len(mvReadMapList)) + if len(env.mvReadMapList) > 0 { + tempDeps := make([][]uint64, len(env.mvReadMapList)) for j := range deps[0] { tempDeps[0] = append(tempDeps[0], uint64(j)) @@ -1116,14 +1110,15 @@ mainloop: delayFlag := true - for i := 1; i <= len(mvReadMapList)-1; i++ { - reads := mvReadMapList[i-1] + for i := 1; i <= len(env.mvReadMapList)-1; i++ { + reads := env.mvReadMapList[i-1] _, ok1 := reads[blockstm.NewSubpathKey(env.coinbase, state.BalancePath)] _, ok2 := reads[blockstm.NewSubpathKey(common.HexToAddress(w.chainConfig.Bor.CalculateBurntContract(env.header.Number.Uint64())), state.BalancePath)] if ok1 || ok2 { delayFlag = false + break } for j := range deps[i] { @@ -1179,7 +1174,7 @@ mainloop: // generateParams wraps various of settings for generating sealing task. type generateParams struct { - timestamp uint64 // The timstamp for sealing task + timestamp uint64 // The timestamp for sealing task forceTime bool // Flag whether the given timestamp is immutable or not parentHash common.Hash // Parent block hash, empty means the latest chain head coinbase common.Address // The fee recipient address for including transaction diff --git a/miner/worker_test.go b/miner/worker_test.go index 58a5ff2948..57bb26511c 100644 --- a/miner/worker_test.go +++ b/miner/worker_test.go @@ -909,7 +909,7 @@ func BenchmarkBorMining(b *testing.B) { } // uses core.NewParallelBlockChain to use the dependencies present in the block header -// params.BorUnittestChainConfig contains the ParallelUniverseBlock ad big.NewInt(5), so the first 4 blocks will not have metadata. +// params.BorUnittestChainConfig contains the NapoliBlock as big.NewInt(5), so the first 4 blocks will not have metadata. // nolint: gocognit func BenchmarkBorMiningBlockSTMMetadata(b *testing.B) { chainConfig := params.BorUnittestChainConfig @@ -949,7 +949,7 @@ func BenchmarkBorMiningBlockSTMMetadata(b *testing.B) { db2 := rawdb.NewMemoryDatabase() back.genesis.MustCommit(db2) - chain, _ := core.NewParallelBlockChain(db2, nil, back.genesis, nil, engine, vm.Config{ParallelEnable: true, ParallelSpeculativeProcesses: 8}, nil, nil, nil) + chain, _ := core.NewParallelBlockChain(db2, nil, back.genesis, nil, engine, vm.Config{}, nil, nil, nil, 8) defer chain.Stop() // Ignore empty commit here for less noise. diff --git a/p2p/msgrate/msgrate.go b/p2p/msgrate/msgrate.go index 36a6cbb213..e1be1e227c 100644 --- a/p2p/msgrate/msgrate.go +++ b/p2p/msgrate/msgrate.go @@ -80,7 +80,7 @@ const ttlLimit = time.Minute // tuningConfidenceCap is the number of active peers above which to stop detuning // the confidence number. The idea here is that once we hone in on the capacity -// of a meaningful number of peers, adding one more should ot have a significant +// of a meaningful number of peers, adding one more should not have a significant // impact on things, so just ron with the originals. const tuningConfidenceCap = 10 diff --git a/p2p/rlpx/rlpx_test.go b/p2p/rlpx/rlpx_test.go index 46ae3eba21..955215eb5c 100644 --- a/p2p/rlpx/rlpx_test.go +++ b/p2p/rlpx/rlpx_test.go @@ -450,7 +450,7 @@ func BenchmarkThroughput(b *testing.B) { conn2.SetSnappy(true) if err := <-handshakeDone; err != nil { - b.Fatal("server hanshake error:", err) + b.Fatal("server handshake error:", err) } // Read N messages. diff --git a/p2p/simulations/adapters/inproc.go b/p2p/simulations/adapters/inproc.go index e8d2d1a886..79faf0ba75 100644 --- a/p2p/simulations/adapters/inproc.go +++ b/p2p/simulations/adapters/inproc.go @@ -177,7 +177,7 @@ type SimNode struct { registerOnce sync.Once } -// Close closes the underlaying node.Node to release +// Close closes the underlying node.Node to release // acquired resources. func (sn *SimNode) Close() error { return sn.node.Close() diff --git a/p2p/simulations/network_test.go b/p2p/simulations/network_test.go index 2eaa0e452a..232d356250 100644 --- a/p2p/simulations/network_test.go +++ b/p2p/simulations/network_test.go @@ -740,7 +740,7 @@ func triggerChecks(ctx context.Context, ids []enode.ID, trigger chan enode.ID, i } } -// \todo: refactor to implement shapshots +// \todo: refactor to implement snapshots // and connect configuration methods once these are moved from // swarm/network/simulations/connect.go func BenchmarkMinimalService(b *testing.B) { diff --git a/packaging/templates/package_scripts/control b/packaging/templates/package_scripts/control index e4f0463fc2..94eeea3661 100644 --- a/packaging/templates/package_scripts/control +++ b/packaging/templates/package_scripts/control @@ -1,5 +1,5 @@ Source: bor -Version: 1.2.0-beta +Version: 1.2.3 Section: develop Priority: standard Maintainer: Polygon diff --git a/packaging/templates/package_scripts/control.arm64 b/packaging/templates/package_scripts/control.arm64 index 04a59510f7..809d705aa6 100644 --- a/packaging/templates/package_scripts/control.arm64 +++ b/packaging/templates/package_scripts/control.arm64 @@ -1,5 +1,5 @@ Source: bor -Version: 1.2.0-beta +Version: 1.2.3 Section: develop Priority: standard Maintainer: Polygon diff --git a/packaging/templates/package_scripts/control.profile.amd64 b/packaging/templates/package_scripts/control.profile.amd64 index f83b21148d..22470ccd49 100644 --- a/packaging/templates/package_scripts/control.profile.amd64 +++ b/packaging/templates/package_scripts/control.profile.amd64 @@ -1,5 +1,5 @@ Source: bor-profile -Version: 1.2.0-beta +Version: 1.2.3 Section: develop Priority: standard Maintainer: Polygon diff --git a/packaging/templates/package_scripts/control.profile.arm64 b/packaging/templates/package_scripts/control.profile.arm64 index e39ecda6d1..4a52b2e063 100644 --- a/packaging/templates/package_scripts/control.profile.arm64 +++ b/packaging/templates/package_scripts/control.profile.arm64 @@ -1,5 +1,5 @@ Source: bor-profile -Version: 1.2.0-beta +Version: 1.2.3 Section: develop Priority: standard Maintainer: Polygon diff --git a/packaging/templates/package_scripts/control.validator b/packaging/templates/package_scripts/control.validator index f201053311..00b517c3b0 100644 --- a/packaging/templates/package_scripts/control.validator +++ b/packaging/templates/package_scripts/control.validator @@ -1,5 +1,5 @@ Source: bor-profile -Version: 1.2.0-beta +Version: 1.2.3 Section: develop Priority: standard Maintainer: Polygon diff --git a/packaging/templates/package_scripts/control.validator.arm64 b/packaging/templates/package_scripts/control.validator.arm64 index fa5360da07..725a4ec394 100644 --- a/packaging/templates/package_scripts/control.validator.arm64 +++ b/packaging/templates/package_scripts/control.validator.arm64 @@ -1,5 +1,5 @@ Source: bor-profile -Version: 1.2.0-beta +Version: 1.2.3 Section: develop Priority: standard Maintainer: Polygon diff --git a/params/config.go b/params/config.go index 45e9f2ef92..5aacfb60a1 100644 --- a/params/config.go +++ b/params/config.go @@ -160,7 +160,6 @@ var ( BerlinBlock: big.NewInt(0), LondonBlock: big.NewInt(0), Bor: &BorConfig{ - ParallelUniverseBlock: big.NewInt(5), Period: map[string]uint64{ "0": 1, }, @@ -199,10 +198,9 @@ var ( LondonBlock: big.NewInt(22640000), ShanghaiBlock: big.NewInt(41874000), Bor: &BorConfig{ - JaipurBlock: big.NewInt(22770000), - DelhiBlock: big.NewInt(29638656), - ParallelUniverseBlock: big.NewInt(0), - IndoreBlock: big.NewInt(37075456), + JaipurBlock: big.NewInt(22770000), + DelhiBlock: big.NewInt(29638656), + IndoreBlock: big.NewInt(37075456), StateSyncConfirmationDelay: map[string]uint64{ "37075456": 128, }, @@ -311,10 +309,9 @@ var ( LondonBlock: big.NewInt(23850000), ShanghaiBlock: big.NewInt(50523000), Bor: &BorConfig{ - JaipurBlock: big.NewInt(23850000), - DelhiBlock: big.NewInt(38189056), - ParallelUniverseBlock: big.NewInt(0), - IndoreBlock: big.NewInt(44934656), + JaipurBlock: big.NewInt(23850000), + DelhiBlock: big.NewInt(38189056), + IndoreBlock: big.NewInt(44934656), StateSyncConfirmationDelay: map[string]uint64{ "44934656": 128, }, @@ -615,7 +612,6 @@ type BorConfig struct { BurntContract map[string]string `json:"burntContract"` // governance contract where the token will be sent to and burnt in london fork JaipurBlock *big.Int `json:"jaipurBlock"` // Jaipur switch block (nil = no fork, 0 = already on jaipur) DelhiBlock *big.Int `json:"delhiBlock"` // Delhi switch block (nil = no fork, 0 = already on delhi) - ParallelUniverseBlock *big.Int `json:"parallelUniverseBlock"` // TODO: update all occurrence, change name and finalize number (hardfork for block-stm related changes) IndoreBlock *big.Int `json:"indoreBlock"` // Indore switch block (nil = no fork, 0 = already on indore) StateSyncConfirmationDelay map[string]uint64 `json:"stateSyncConfirmationDelay"` // StateSync Confirmation Delay, in seconds, to calculate `to` } @@ -657,16 +653,16 @@ func (c *BorConfig) CalculateStateSyncDelay(number uint64) uint64 { return borKeyValueConfigHelper(c.StateSyncConfirmationDelay, number) } -// TODO: modify this function once the block number is finalized -func (c *BorConfig) IsParallelUniverse(number *big.Int) bool { - if c.ParallelUniverseBlock != nil { - if c.ParallelUniverseBlock.Cmp(big.NewInt(0)) == 0 { - return false - } - } +// // TODO: modify this function once the block number is finalized +// func (c *BorConfig) IsNapoli(number *big.Int) bool { +// if c.NapoliBlock != nil { +// if c.NapoliBlock.Cmp(big.NewInt(0)) == 0 { +// return false +// } +// } - return isBlockForked(c.ParallelUniverseBlock, number) -} +// return isBlockForked(c.NapoliBlock, number) +// } func (c *BorConfig) IsSprintStart(number uint64) bool { return number%c.CalculateSprint(number) == 0 @@ -960,9 +956,9 @@ func (c *ChainConfig) CheckConfigForkOrder() error { {name: "arrowGlacierBlock", block: c.ArrowGlacierBlock, optional: true}, {name: "grayGlacierBlock", block: c.GrayGlacierBlock, optional: true}, {name: "mergeNetsplitBlock", block: c.MergeNetsplitBlock, optional: true}, - {name: "shanghaiBlock", block: c.ShanghaiBlock}, - {name: "cancunBlock", block: c.CancunBlock, optional: true}, - {name: "pragueBlock", block: c.PragueBlock, optional: true}, + {name: "ShanghaiBlock", block: c.ShanghaiBlock}, + {name: "CancunBlock", block: c.CancunBlock, optional: true}, + {name: "pragueTime", block: c.PragueBlock, optional: true}, } { if lastFork.name != "" { switch { diff --git a/params/version.go b/params/version.go index d942ddf483..b44ab8079c 100644 --- a/params/version.go +++ b/params/version.go @@ -21,10 +21,10 @@ import ( ) const ( - VersionMajor = 1 // Major version component of the current release - VersionMinor = 2 // Minor version component of the current release - VersionPatch = 0 // Patch version component of the current release - VersionMeta = "beta" // Version metadata to append to the version string + VersionMajor = 1 // Major version component of the current release + VersionMinor = 2 // Minor version component of the current release + VersionPatch = 3 // Patch version component of the current release + VersionMeta = "" // Version metadata to append to the version string ) var GitCommit string diff --git a/rlp/rlpgen/gen.go b/rlp/rlpgen/gen.go index e0bdc75bb5..ce427f601b 100644 --- a/rlp/rlpgen/gen.go +++ b/rlp/rlpgen/gen.go @@ -166,7 +166,7 @@ type op interface { // basicOp handles basic types bool, uint*, string. type basicOp struct { typ types.Type - writeMethod string // calle write the value + writeMethod string // calls write value writeArgType types.Type // parameter type of writeMethod decMethod string decResultType types.Type // return type of decMethod diff --git a/signer/core/api.go b/signer/core/api.go index cd505c720a..0691e98a58 100644 --- a/signer/core/api.go +++ b/signer/core/api.go @@ -692,7 +692,7 @@ func (api *SignerAPI) SignGnosisSafeTx(ctx context.Context, signerAddress common } typedData := gnosisTx.ToTypedData() - // might aswell error early. + // might as well error early. // we are expected to sign. If our calculated hash does not match what they want, // The gnosis safetx input contains a 'safeTxHash' which is the expected safeTxHash that sighash, _, err := apitypes.TypedDataAndHash(typedData) diff --git a/tests/bor/bor_test.go b/tests/bor/bor_test.go index 07c9ecc5dc..ec389a30ca 100644 --- a/tests/bor/bor_test.go +++ b/tests/bor/bor_test.go @@ -298,7 +298,7 @@ func TestForkWithBlockTime(t *testing.T) { // Iterate over all the nodes and start mining for _, node := range nodes { if err := node.StartMining(); err != nil { - t.Fatal("Error occured while starting miner", "node", node, "error", err) + t.Fatal("Error occurred while starting miner", "node", node, "error", err) } } var wg sync.WaitGroup @@ -332,22 +332,22 @@ func TestForkWithBlockTime(t *testing.T) { author0, err := nodes[0].Engine().Author(blockHeaderVal0) if err != nil { - t.Error("Error occured while fetching author", "err", err) + t.Error("Error occurred while fetching author", "err", err) } author1, err := nodes[1].Engine().Author(blockHeaderVal1) if err != nil { - t.Error("Error occured while fetching author", "err", err) + t.Error("Error occurred while fetching author", "err", err) } assert.Equal(t, author0, author1) // After the end of sprint author2, err := nodes[0].Engine().Author(blockHeaders[0]) if err != nil { - t.Error("Error occured while fetching author", "err", err) + t.Error("Error occurred while fetching author", "err", err) } author3, err := nodes[1].Engine().Author(blockHeaders[1]) if err != nil { - t.Error("Error occured while fetching author", "err", err) + t.Error("Error occurred while fetching author", "err", err) } if test.forkExpected { diff --git a/tests/bor/helper.go b/tests/bor/helper.go index cc17dc9647..2d3dd030e5 100644 --- a/tests/bor/helper.go +++ b/tests/bor/helper.go @@ -91,7 +91,7 @@ func setupMiner(t *testing.T, n int, genesis *core.Genesis) ([]*node.Node, []*et // Start the node and wait until it's up stack, ethBackend, err := InitMiner(genesis, keys[i], true) if err != nil { - t.Fatal("Error occured while initialising miner", "error", err) + t.Fatal("Error occurred while initialising miner", "error", err) } for stack.Server().NodeInfo().Ports.Listener == 0 { diff --git a/trie/proof.go b/trie/proof.go index 55edb54669..0a0e9257d5 100644 --- a/trie/proof.go +++ b/trie/proof.go @@ -428,7 +428,7 @@ func unset(parent node, child node, key []byte, pos int, removeLeft bool) error } else { if bytes.Compare(cld.Key, key[pos:]) > 0 { // The key of fork shortnode is greater than the - // path(it belongs to the range), unset the entrie + // path(it belongs to the range), unset the entire // branch. The parent must be a fullnode. fn := parent.(*fullNode) fn.Children[key[pos-1]] = nil diff --git a/trie/sync.go b/trie/sync.go index 48918908bb..fa3f94ec6d 100644 --- a/trie/sync.go +++ b/trie/sync.go @@ -302,7 +302,7 @@ func (s *Sync) Missing(max int) ([]string, []common.Hash, []common.Hash) { } // ProcessCode injects the received data for requested item. Note it can -// happpen that the single response commits two pending requests(e.g. +// happen that the single response commits two pending requests(e.g. // there are two requests one for code and one for node but the hash // is same). In this case the second response for the same hash will // be treated as "non-requested" item or "already-processed" item but diff --git a/trie/trie_test.go b/trie/trie_test.go index a4a7ed17a4..9eaf4676c5 100644 --- a/trie/trie_test.go +++ b/trie/trie_test.go @@ -349,7 +349,7 @@ func TestLargeValue(t *testing.T) { trie.Hash() } -// TestRandomCases tests som cases that were found via random fuzzing +// TestRandomCases tests some cases that were found via random fuzzing func TestRandomCases(t *testing.T) { var rt = []randTestStep{ {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 0