Skip to content

Commit faad758

Browse files
committed
cleanups and documentation
1 parent 39abcf1 commit faad758

File tree

5 files changed

+51
-84
lines changed

5 files changed

+51
-84
lines changed

core/blockchain.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1892,10 +1892,9 @@ func (bc *BlockChain) insertChain(chain types.Blocks, setHead bool, makeWitness
18921892
start := time.Now()
18931893

18941894
blockHasAccessList := block.Body().AccessList != nil
1895-
// BAL generation/verification not enabled pre-selfdestruct removal
1896-
1897-
// TODO: state diff recording will be activated any time it's cancun.
1898-
// This shouldn't happen....
1895+
// BAL generation/verification is not enabled pre-selfdestruct removal.
1896+
// TODO: there is a bug where state diff recording will be activated if
1897+
// cancun is enabled, this should be fixed before merging!
18991898
forkSupportsBAL := bc.chainConfig.IsCancun(block.Number(), block.Time())
19001899
makeBAL := forkSupportsBAL && !blockHasAccessList
19011900
validateBAL := forkSupportsBAL && blockHasAccessList
@@ -2025,6 +2024,7 @@ func (bc *BlockChain) processBlock(parentRoot common.Hash, block *types.Block, s
20252024
vmCfg := bc.cfg.VmConfig
20262025
vmCfg.Tracer = nil
20272026
if block.Body().AccessList == nil {
2027+
// only use the state prefetcher for non-BAL blocks.
20282028
bc.prefetcher.Prefetch(block, throwaway, vmCfg, &interrupt)
20292029
}
20302030

core/state/state_object.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,6 @@ func (s *stateObject) finalise() *bal.AccountState {
285285
// to avoid thrashing the data structures.
286286
delete(s.uncommittedStorage, key)
287287

288-
// TODO: ensure that we should record the diff here: i.e. this storage slot had a different val at the start of the transaction
289288
if s.db.enableStateDiffRecording {
290289
if s.db.constructionBAL != nil {
291290
s.db.BlockAccessList().StorageWrite(uint16(s.db.balIndex), s.address, key, value)
@@ -638,6 +637,7 @@ func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
638637
s.data.CodeHash = codeHash[:]
639638
}
640639

640+
// setCode sets the code and hash and dirty markers.
641641
func (s *stateObject) setCodeModified(codeHash common.Hash, code []byte) {
642642
s.setCode(codeHash, code)
643643
s.dirtyCode = true

core/state/statedb.go

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,8 @@ func (s *StateDB) AddRefund(gas uint64) {
318318
s.refund += gas
319319
}
320320

321+
// InstantiateWithStateDiffs instantiates the live object based on accounts
322+
// which appeared in the total state diff of a block, and were also preexisting.
321323
func (s *StateDB) InstantiateWithStateDiffs(totalDiff *bal.StateDiff) {
322324
stateAccounts := new(sync.Map)
323325
wg := new(sync.WaitGroup)
@@ -826,14 +828,11 @@ func (s *StateDB) Finalise(deleteEmptyObjects bool) (diff *bal.StateDiff) {
826828
continue
827829
}
828830
if obj.selfDestructed || (deleteEmptyObjects && obj.empty()) {
829-
// TODO: for testing purposes we should probably have tests that create/destroy the same account multiple times via this same edge-case with create2
830-
if obj.txPreBalance != nil && !obj.txPreBalance.IsZero() { // TODO: IsZero check is somehow needed for coinbase. figure out why.
831-
// TODO: need to ensure that we aren't recording accounts in the state diff/BAL which were created/selfdestructed in the same transaction.
832-
// It should be as easy as modifying the check above to not include selfdestructed contracts. However, doing this causes some blockchain tests
833-
// to fail and I'm not sure why.
834-
//
835-
// TODO: the coinbase can be touched and then become empty here: see BlockchainBAL/GeneralStateTests/stExample/solidityExample.json/solidityExample_d0g0v0_Cancun
836-
// ^ coinbase probably shouldn't be in the BAL/statediff in this case.
831+
// record state diffs for any preexisting accounts which became empty
832+
if s.enableStateDiffRecording && obj.txPreBalance != nil && !obj.txPreBalance.IsZero() {
833+
// TODO: IsZero check is somehow needed for coinbase. figure out why.
834+
// TODO: the above check should be as easy as checking that the account was not selfdestructed in the
835+
// current transaction, but that causes spec tests to fail. need to figure out why.
837836
if s.constructionBAL != nil {
838837
s.constructionBAL.BalanceChange(uint16(s.balIndex), obj.address, uint256.NewInt(0))
839838
}
@@ -855,7 +854,7 @@ func (s *StateDB) Finalise(deleteEmptyObjects bool) (diff *bal.StateDiff) {
855854

856855
if s.enableStateDiffRecording && (accountPost.Nonce != nil || accountPost.Code != nil || accountPost.StorageWrites != nil || accountPost.Balance != nil) {
857856
// the account executed SENDALL but did not send a balance, don't include it in the diff
858-
// TODO: probably shouldn't include the account in the dirty set in this case
857+
// TODO: probably shouldn't include the account in the dirty set in this case (unrelated to the BAL changes)
859858
diff.Mutations[obj.address] = accountPost
860859
}
861860
s.markUpdate(addr)
@@ -1062,6 +1061,7 @@ func (s *StateDB) SetTxSender(sender common.Address) {
10621061
s.sender = sender
10631062
}
10641063

1064+
// ApplyPrestate applies finalised pre-state changes which occurred between the start of the block and the end of the previous transaction.
10651065
func (s *StateDB) ApplyPrestate(prestateDiff *bal.StateDiff) {
10661066
for addr, accountDiff := range prestateDiff.Mutations {
10671067
stateObject, preexisting := s.stateObjects[addr]
@@ -1110,6 +1110,8 @@ func (s *StateDB) ApplyPrestate(prestateDiff *bal.StateDiff) {
11101110
}
11111111
}
11121112

1113+
// ApplyStateDiff applies a state diff to the StateDB. All state changes will be marked as mutations
1114+
// for the purpose of applying them in the next call to Commit.
11131115
func (s *StateDB) ApplyStateDiff(diff *bal.StateDiff) {
11141116
for addr, accountDiff := range diff.Mutations {
11151117
stateObject, ok := s.stateObjects[addr]

core/state_processor.go

Lines changed: 29 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,8 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
158158
}, nil
159159
}
160160

161+
// ProcessWithAccessList performs EVM execution and state root computation for a block which is known
162+
// to contain an access list.
161163
func (p *StateProcessor) ProcessWithAccessList(block *types.Block, statedb *state.StateDB, cfg vm.Config) (chan *ProcessResultWithMetrics, error) {
162164
var (
163165
header = block.Header()
@@ -179,12 +181,12 @@ func (p *StateProcessor) ProcessWithAccessList(block *types.Block, statedb *stat
179181
rootCalcErrCh := make(chan error) // used for communicating if the state root calculation doesn't match the reported root
180182
pStart := time.Now()
181183
var (
182-
tPreprocess time.Duration
184+
tPreprocess time.Duration // time to create a set of prestates for parallel transaction execution
183185
tVerifyStart time.Time
184-
tVerify time.Duration
186+
tVerify time.Duration // time to compute and verify the state root
185187
tExecStart time.Time
186-
tExec time.Duration
187-
tPostprocess time.Duration
188+
tExec time.Duration // time to execute block transactions
189+
tPostprocess time.Duration // time to perform post-transaction execution system calls and withdrawals.
188190
)
189191

190192
// called by resultHandler when all transactions have successfully executed.
@@ -252,9 +254,6 @@ func (p *StateProcessor) ProcessWithAccessList(block *types.Block, statedb *stat
252254
finalDiff := postTxState.Finalise(true)
253255
computedDiff.Merge(finalDiff)
254256

255-
// TODO: at each step, we should only be comparing the "intermediate" state diffs
256-
// not the entire state diff up until that point.
257-
258257
if err := bal.ValidateStateDiff(expectedStateDiff, computedDiff); err != nil {
259258
return &ProcessResult{
260259
Error: fmt.Errorf("post-transaction-execution state transition produced a different diff that what was reported in the BAL"),
@@ -340,12 +339,12 @@ func (p *StateProcessor) ProcessWithAccessList(block *types.Block, statedb *stat
340339
execTx := func(ctx context2.Context, tx *types.Transaction, idx int, db *state.StateDB, prestateDiff, expectedDiff *bal.StateDiff) *txExecResult {
341340
db.ApplyPrestate(prestateDiff)
342341
// if an error with another transaction rendered the block invalid, don't proceed with executing this one
343-
// TODO: also interrupt any currently-executing transactions if one failed.
344342
select {
345343
case <-ctx.Done():
346344
return &txExecResult{err: ctx.Err()}
347345
default:
348346
}
347+
// TODO: also interrupt any currently-executing transactions if one failed.
349348
var tracingStateDB = vm.StateDB(db)
350349
if hooks := cfg.Tracer; hooks != nil {
351350
tracingStateDB = state.NewHookedState(db, hooks)
@@ -362,7 +361,7 @@ func (p *StateProcessor) ProcessWithAccessList(block *types.Block, statedb *stat
362361
db.SetTxSender(sender)
363362
db.SetTxContext(tx.Hash(), idx)
364363

365-
evm.StateDB = db // TODO: unsure if need to set this here since the evm should maintain a reference to the db but I recall that adding this fixed some broken tests
364+
evm.StateDB = db
366365
gp := new(GasPool)
367366
gp.SetGas(block.GasLimit())
368367
var gasUsed uint64
@@ -398,47 +397,47 @@ func (p *StateProcessor) ProcessWithAccessList(block *types.Block, statedb *stat
398397
context = NewEVMBlockContext(header, p.chain, nil)
399398
evm := vm.NewEVM(context, tracingStateDB, p.config, cfg)
400399

401-
// process beacon-root and parent block system contracts.
402-
// do not include the storage writes in the BAL:
403-
// * beacon root will be provided as a standalone field in the BAL
404-
// * parent block hash is already in the header field of the block
405-
400+
// convert the BAL entries into an ordered list of state diffs per index
406401
intermediateStateDiffs := bal.BuildStateDiffs(block.Body().AccessList, len(block.Transactions()))
407402
preTxDiff := intermediateStateDiffs[0]
408403

409-
totalDiff := bal.StateDiff{make(map[common.Address]*bal.AccountState)}
410-
var totalDiffs []*bal.StateDiff
411-
for _, diff := range intermediateStateDiffs {
412-
totalDiff.Merge(diff.Copy()) // TODO: it shouldn't be necessary to Copy here
413-
totalDiffs = append(totalDiffs, totalDiff.Copy())
414-
}
415-
statedb.InstantiateWithStateDiffs(&totalDiff)
416-
417-
computedDiff := &bal.StateDiff{make(map[common.Address]*bal.AccountState)}
404+
// validate the correctness of pre-transaction execution state changes
405+
computedPreTxDiff := &bal.StateDiff{make(map[common.Address]*bal.AccountState)}
418406
if beaconRoot := block.BeaconRoot(); beaconRoot != nil {
419-
computedDiff.Merge(ProcessBeaconBlockRoot(*beaconRoot, evm))
407+
computedPreTxDiff.Merge(ProcessBeaconBlockRoot(*beaconRoot, evm))
420408
}
421409
if p.config.IsPrague(block.Number(), block.Time()) || p.config.IsVerkle(block.Number(), block.Time()) {
422-
computedDiff.Merge(ProcessParentBlockHash(block.ParentHash(), evm))
410+
computedPreTxDiff.Merge(ProcessParentBlockHash(block.ParentHash(), evm))
423411
}
424-
425-
if err := bal.ValidateStateDiff(preTxDiff, computedDiff); err != nil {
412+
if err := bal.ValidateStateDiff(preTxDiff, computedPreTxDiff); err != nil {
426413
return nil, err
427414
}
428415

429-
var txPrestates []*state.StateDB
416+
// compute the aggregate state diff of the block
417+
totalDiff := bal.StateDiff{make(map[common.Address]*bal.AccountState)}
418+
var totalDiffs []*bal.StateDiff
419+
for _, diff := range intermediateStateDiffs {
420+
totalDiff.Merge(diff.Copy()) // TODO: it shouldn't be necessary to Copy here
421+
totalDiffs = append(totalDiffs, totalDiff.Copy())
422+
}
430423

431-
// Iterate over and process the individual transactions
424+
// instantiate a set of StateDBs to be used for executing each transaction in parallel
425+
statedb.InstantiateWithStateDiffs(&totalDiff)
426+
var txPrestates []*state.StateDB
432427
for range block.Transactions() {
433428
state := statedb.Copy()
434429
txPrestates = append(txPrestates, state)
435430
}
431+
432+
// compute the post-tx state prestate (before applying final block system calls and eip-4895 withdrawals)
436433
postTxState := statedb.Copy()
437-
postTxState.ApplyStateDiff(totalDiffs[len(totalDiffs)-2])
434+
postTxState.ApplyPrestate(totalDiffs[len(totalDiffs)-2])
438435
postTxState.Finalise(true)
439436

440437
tPreprocess = time.Since(pStart)
441438

439+
// execute transactions and state root calculation in parallel
440+
442441
tExecStart = time.Now()
443442
go resultHandler(intermediateStateDiffs[len(block.Transactions())+1], postTxState)
444443
var workers errgroup.Group
@@ -455,7 +454,6 @@ func (p *StateProcessor) ProcessWithAccessList(block *types.Block, statedb *stat
455454

456455
statedb.ApplyStateDiff(&totalDiff)
457456
statedb.Finalise(true)
458-
//fmt.Printf("total diff is\n%s\napplied diff is\n%s\n", totalDiff.String(), appliedDiff.String())
459457
go calcAndVerifyRoot(statedb.Copy(), block, rootCalcErrCh)
460458

461459
return resCh, nil

core/types/bal/bal_encoding.go

Lines changed: 6 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -380,10 +380,8 @@ type AccountState struct {
380380
StorageWrites map[common.Hash]common.Hash `json:"StorageWrites,omitempty"`
381381
}
382382

383-
func (a *AccountState) IsEmpty() bool {
384-
return a.Balance == nil || a.Balance.IsZero() || a.Nonce == nil || a.Code == nil
385-
}
386-
383+
// Merge the changes of a future AccountState into the caller, resulting in the
384+
// combined state changes through next.
387385
func (a *AccountState) Merge(next *AccountState) {
388386
if next.Balance != nil {
389387
a.Balance = next.Balance
@@ -474,7 +472,7 @@ func (a *AccountState) Copy() *AccountState {
474472
return res
475473
}
476474

477-
// ValidateStateDiff asserts that the state from layerDiff are present in totalDiffAtLayer.
475+
// ValidateStateDiff asserts that both state diffs are equivalent.
478476
func ValidateStateDiff(balDiff, computedDiff *StateDiff) error {
479477
for addr, computedAccountDiff := range computedDiff.Mutations {
480478
balAccountDiff, ok := balDiff.Mutations[addr]
@@ -500,7 +498,8 @@ func (s *StateDiff) String() string {
500498
return res.String()
501499
}
502500

503-
// merge the future state from next into the current diff modifying the caller
501+
// Merge merges the state changes present in next into the caller. After,
502+
// the state of the caller is the aggregate diff through next.
504503
func (s *StateDiff) Merge(next *StateDiff) {
505504
for account, diff := range next.Mutations {
506505
if mut, ok := s.Mutations[account]; ok {
@@ -529,35 +528,6 @@ func (s *StateDiff) Merge(next *StateDiff) {
529528
}
530529
}
531530

532-
func (s *StateDiff) MergePrev(prev *StateDiff) {
533-
for account, diff := range prev.Mutations {
534-
if mut, ok := s.Mutations[account]; ok {
535-
if mut.Balance == nil {
536-
mut.Balance = diff.Balance
537-
}
538-
if mut.Code == nil {
539-
mut.Code = diff.Code
540-
}
541-
if mut.Nonce == nil {
542-
mut.Nonce = diff.Nonce
543-
}
544-
if len(diff.StorageWrites) > 0 {
545-
if mut.StorageWrites == nil {
546-
mut.StorageWrites = diff.StorageWrites
547-
} else {
548-
for key, val := range diff.StorageWrites {
549-
if _, ok := mut.StorageWrites[key]; !ok {
550-
mut.StorageWrites[key] = val
551-
}
552-
}
553-
}
554-
}
555-
} else {
556-
s.Mutations[account] = diff
557-
}
558-
}
559-
}
560-
561531
func (s *StateDiff) Copy() *StateDiff {
562532
res := &StateDiff{make(map[common.Address]*AccountState)}
563533
for addr, accountDiff := range s.Mutations {
@@ -685,10 +655,7 @@ func (it *BALIterator) Next() (mutations *StateDiff) {
685655
return &diff
686656
}
687657

688-
// BuildStateDiffs returns a set of ordered state diffs from the BAL
689-
// corresponding to each txIndex. "until" is specified as the maximum
690-
// index which will be contained in the result.
691-
// It returns the aggregated state diff of all layers and a state diff for each layer.
658+
// BuildStateDiffs computes the ordered set of state diffs from an access list.
692659
func BuildStateDiffs(bal *BlockAccessList, txCount int) []*StateDiff {
693660
stateDiffs := make([]*StateDiff, txCount+2)
694661
for i := 0; i < len(stateDiffs); i++ {

0 commit comments

Comments
 (0)