Skip to content

Commit 43cbcd7

Browse files
authored
core, core/state: move TriesInMemory to state package (#29701)
1 parent a09a610 commit 43cbcd7

File tree

3 files changed

+32
-30
lines changed

3 files changed

+32
-30
lines changed

core/blockchain.go

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,6 @@ const (
100100
blockCacheLimit = 256
101101
receiptsCacheLimit = 32
102102
txLookupCacheLimit = 1024
103-
TriesInMemory = 128
104103

105104
// BlockChainVersion ensures that an incompatible database forces a resync from scratch.
106105
//
@@ -1128,7 +1127,7 @@ func (bc *BlockChain) Stop() {
11281127
if !bc.cacheConfig.TrieDirtyDisabled {
11291128
triedb := bc.triedb
11301129

1131-
for _, offset := range []uint64{0, 1, TriesInMemory - 1} {
1130+
for _, offset := range []uint64{0, 1, state.TriesInMemory - 1} {
11321131
if number := bc.CurrentBlock().Number.Uint64(); number > offset {
11331132
recent := bc.GetBlockByNumber(number - offset)
11341133

@@ -1452,7 +1451,7 @@ func (bc *BlockChain) writeKnownBlock(block *types.Block) error {
14521451

14531452
// writeBlockWithState writes block, metadata and corresponding state data to the
14541453
// database.
1455-
func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) error {
1454+
func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, statedb *state.StateDB) error {
14561455
// Calculate the total difficulty of the block
14571456
ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
14581457
if ptd == nil {
@@ -1469,12 +1468,12 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.
14691468
rawdb.WriteTd(blockBatch, block.Hash(), block.NumberU64(), externTd)
14701469
rawdb.WriteBlock(blockBatch, block)
14711470
rawdb.WriteReceipts(blockBatch, block.Hash(), block.NumberU64(), receipts)
1472-
rawdb.WritePreimages(blockBatch, state.Preimages())
1471+
rawdb.WritePreimages(blockBatch, statedb.Preimages())
14731472
if err := blockBatch.Write(); err != nil {
14741473
log.Crit("Failed to write block into disk", "err", err)
14751474
}
14761475
// Commit all cached state changes into underlying memory database.
1477-
root, err := state.Commit(block.NumberU64(), bc.chainConfig.IsEIP158(block.Number()))
1476+
root, err := statedb.Commit(block.NumberU64(), bc.chainConfig.IsEIP158(block.Number()))
14781477
if err != nil {
14791478
return err
14801479
}
@@ -1493,7 +1492,7 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.
14931492

14941493
// Flush limits are not considered for the first TriesInMemory blocks.
14951494
current := block.NumberU64()
1496-
if current <= TriesInMemory {
1495+
if current <= state.TriesInMemory {
14971496
return nil
14981497
}
14991498
// If we exceeded our memory allowance, flush matured singleton nodes to disk
@@ -1505,7 +1504,7 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.
15051504
bc.triedb.Cap(limit - ethdb.IdealBatchSize)
15061505
}
15071506
// Find the next state trie we need to commit
1508-
chosen := current - TriesInMemory
1507+
chosen := current - state.TriesInMemory
15091508
flushInterval := time.Duration(bc.flushInterval.Load())
15101509
// If we exceeded time allowance, flush an entire trie to disk
15111510
if bc.gcproc > flushInterval {
@@ -1517,8 +1516,8 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.
15171516
} else {
15181517
// If we're exceeding limits but haven't reached a large enough memory gap,
15191518
// warn the user that the system is becoming unstable.
1520-
if chosen < bc.lastWrite+TriesInMemory && bc.gcproc >= 2*flushInterval {
1521-
log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", flushInterval, "optimum", float64(chosen-bc.lastWrite)/TriesInMemory)
1519+
if chosen < bc.lastWrite+state.TriesInMemory && bc.gcproc >= 2*flushInterval {
1520+
log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", flushInterval, "optimum", float64(chosen-bc.lastWrite)/state.TriesInMemory)
15221521
}
15231522
// Flush an entire trie and restart the counters
15241523
bc.triedb.Commit(header.Root, true)

core/blockchain_test.go

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1712,7 +1712,7 @@ func TestTrieForkGC(t *testing.T) {
17121712
Config: params.TestChainConfig,
17131713
BaseFee: big.NewInt(params.InitialBaseFee),
17141714
}
1715-
genDb, blocks, _ := GenerateChainWithGenesis(genesis, engine, 2*TriesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
1715+
genDb, blocks, _ := GenerateChainWithGenesis(genesis, engine, 2*state.TriesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
17161716

17171717
// Generate a bunch of fork blocks, each side forking from the canonical chain
17181718
forks := make([]*types.Block, len(blocks))
@@ -1740,7 +1740,7 @@ func TestTrieForkGC(t *testing.T) {
17401740
}
17411741
}
17421742
// Dereference all the recent tries and ensure no past trie is left in
1743-
for i := 0; i < TriesInMemory; i++ {
1743+
for i := 0; i < state.TriesInMemory; i++ {
17441744
chain.TrieDB().Dereference(blocks[len(blocks)-1-i].Root())
17451745
chain.TrieDB().Dereference(forks[len(blocks)-1-i].Root())
17461746
}
@@ -1764,8 +1764,8 @@ func testLargeReorgTrieGC(t *testing.T, scheme string) {
17641764
BaseFee: big.NewInt(params.InitialBaseFee),
17651765
}
17661766
genDb, shared, _ := GenerateChainWithGenesis(genesis, engine, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
1767-
original, _ := GenerateChain(genesis.Config, shared[len(shared)-1], engine, genDb, 2*TriesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
1768-
competitor, _ := GenerateChain(genesis.Config, shared[len(shared)-1], engine, genDb, 2*TriesInMemory+1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{3}) })
1767+
original, _ := GenerateChain(genesis.Config, shared[len(shared)-1], engine, genDb, 2*state.TriesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
1768+
competitor, _ := GenerateChain(genesis.Config, shared[len(shared)-1], engine, genDb, 2*state.TriesInMemory+1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{3}) })
17691769

17701770
// Import the shared chain and the original canonical one
17711771
db, _ := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), t.TempDir(), "", false)
@@ -1804,7 +1804,7 @@ func testLargeReorgTrieGC(t *testing.T, scheme string) {
18041804
}
18051805
// In path-based trie database implementation, it will keep 128 diff + 1 disk
18061806
// layers, totally 129 latest states available. In hash-based it's 128.
1807-
states := TriesInMemory
1807+
states := state.TriesInMemory
18081808
if scheme == rawdb.PathScheme {
18091809
states = states + 1
18101810
}
@@ -1972,7 +1972,7 @@ func testLowDiffLongChain(t *testing.T, scheme string) {
19721972
}
19731973
// We must use a pretty long chain to ensure that the fork doesn't overtake us
19741974
// until after at least 128 blocks post tip
1975-
genDb, blocks, _ := GenerateChainWithGenesis(genesis, engine, 6*TriesInMemory, func(i int, b *BlockGen) {
1975+
genDb, blocks, _ := GenerateChainWithGenesis(genesis, engine, 6*state.TriesInMemory, func(i int, b *BlockGen) {
19761976
b.SetCoinbase(common.Address{1})
19771977
b.OffsetTime(-9)
19781978
})
@@ -1992,7 +1992,7 @@ func testLowDiffLongChain(t *testing.T, scheme string) {
19921992
}
19931993
// Generate fork chain, starting from an early block
19941994
parent := blocks[10]
1995-
fork, _ := GenerateChain(genesis.Config, parent, engine, genDb, 8*TriesInMemory, func(i int, b *BlockGen) {
1995+
fork, _ := GenerateChain(genesis.Config, parent, engine, genDb, 8*state.TriesInMemory, func(i int, b *BlockGen) {
19961996
b.SetCoinbase(common.Address{2})
19971997
})
19981998

@@ -2055,7 +2055,7 @@ func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommon
20552055
// Set the terminal total difficulty in the config
20562056
gspec.Config.TerminalTotalDifficulty = big.NewInt(0)
20572057
}
2058-
genDb, blocks, _ := GenerateChainWithGenesis(gspec, engine, 2*TriesInMemory, func(i int, gen *BlockGen) {
2058+
genDb, blocks, _ := GenerateChainWithGenesis(gspec, engine, 2*state.TriesInMemory, func(i int, gen *BlockGen) {
20592059
tx, err := types.SignTx(types.NewTransaction(nonce, common.HexToAddress("deadbeef"), big.NewInt(100), 21000, big.NewInt(int64(i+1)*params.GWei), nil), signer, key)
20602060
if err != nil {
20612061
t.Fatalf("failed to create tx: %v", err)
@@ -2070,9 +2070,9 @@ func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommon
20702070
t.Fatalf("block %d: failed to insert into chain: %v", n, err)
20712071
}
20722072

2073-
lastPrunedIndex := len(blocks) - TriesInMemory - 1
2073+
lastPrunedIndex := len(blocks) - state.TriesInMemory - 1
20742074
lastPrunedBlock := blocks[lastPrunedIndex]
2075-
firstNonPrunedBlock := blocks[len(blocks)-TriesInMemory]
2075+
firstNonPrunedBlock := blocks[len(blocks)-state.TriesInMemory]
20762076

20772077
// Verify pruning of lastPrunedBlock
20782078
if chain.HasBlockAndState(lastPrunedBlock.Hash(), lastPrunedBlock.NumberU64()) {
@@ -2099,7 +2099,7 @@ func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommon
20992099
// Generate fork chain, make it longer than canon
21002100
parentIndex := lastPrunedIndex + blocksBetweenCommonAncestorAndPruneblock
21012101
parent := blocks[parentIndex]
2102-
fork, _ := GenerateChain(gspec.Config, parent, engine, genDb, 2*TriesInMemory, func(i int, b *BlockGen) {
2102+
fork, _ := GenerateChain(gspec.Config, parent, engine, genDb, 2*state.TriesInMemory, func(i int, b *BlockGen) {
21032103
b.SetCoinbase(common.Address{2})
21042104
if int(b.header.Number.Uint64()) >= mergeBlock {
21052105
b.SetPoS()
@@ -2742,7 +2742,7 @@ func testSideImportPrunedBlocks(t *testing.T, scheme string) {
27422742
BaseFee: big.NewInt(params.InitialBaseFee),
27432743
}
27442744
// Generate and import the canonical chain
2745-
_, blocks, _ := GenerateChainWithGenesis(genesis, engine, 2*TriesInMemory, nil)
2745+
_, blocks, _ := GenerateChainWithGenesis(genesis, engine, 2*state.TriesInMemory, nil)
27462746

27472747
chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), DefaultCacheConfigWithScheme(scheme), genesis, nil, engine, vm.Config{}, nil, nil)
27482748
if err != nil {
@@ -2755,9 +2755,9 @@ func testSideImportPrunedBlocks(t *testing.T, scheme string) {
27552755
}
27562756
// In path-based trie database implementation, it will keep 128 diff + 1 disk
27572757
// layers, totally 129 latest states available. In hash-based it's 128.
2758-
states := TriesInMemory
2758+
states := state.TriesInMemory
27592759
if scheme == rawdb.PathScheme {
2760-
states = TriesInMemory + 1
2760+
states = state.TriesInMemory + 1
27612761
}
27622762
lastPrunedIndex := len(blocks) - states - 1
27632763
lastPrunedBlock := blocks[lastPrunedIndex]
@@ -3638,7 +3638,7 @@ func testSetCanonical(t *testing.T, scheme string) {
36383638
engine = ethash.NewFaker()
36393639
)
36403640
// Generate and import the canonical chain
3641-
_, canon, _ := GenerateChainWithGenesis(gspec, engine, 2*TriesInMemory, func(i int, gen *BlockGen) {
3641+
_, canon, _ := GenerateChainWithGenesis(gspec, engine, 2*state.TriesInMemory, func(i int, gen *BlockGen) {
36423642
tx, err := types.SignTx(types.NewTransaction(gen.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, gen.header.BaseFee, nil), signer, key)
36433643
if err != nil {
36443644
panic(err)
@@ -3659,7 +3659,7 @@ func testSetCanonical(t *testing.T, scheme string) {
36593659
}
36603660

36613661
// Generate the side chain and import them
3662-
_, side, _ := GenerateChainWithGenesis(gspec, engine, 2*TriesInMemory, func(i int, gen *BlockGen) {
3662+
_, side, _ := GenerateChainWithGenesis(gspec, engine, 2*state.TriesInMemory, func(i int, gen *BlockGen) {
36633663
tx, err := types.SignTx(types.NewTransaction(gen.TxNonce(address), common.Address{0x00}, big.NewInt(1), params.TxGas, gen.header.BaseFee, nil), signer, key)
36643664
if err != nil {
36653665
panic(err)
@@ -3698,8 +3698,8 @@ func testSetCanonical(t *testing.T, scheme string) {
36983698
verify(side[len(side)-1])
36993699

37003700
// Reset the chain head to original chain
3701-
chain.SetCanonical(canon[TriesInMemory-1])
3702-
verify(canon[TriesInMemory-1])
3701+
chain.SetCanonical(canon[state.TriesInMemory-1])
3702+
verify(canon[state.TriesInMemory-1])
37033703
}
37043704

37053705
// TestCanonicalHashMarker tests all the canonical hash markers are updated/deleted

core/state/statedb.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ import (
4141
"golang.org/x/sync/errgroup"
4242
)
4343

44+
// TriesInMemory represents the number of layers that are kept in RAM.
45+
const TriesInMemory = 128
46+
4447
type revision struct {
4548
id int
4649
journalIndex int
@@ -1269,12 +1272,12 @@ func (s *StateDB) Commit(block uint64, deleteEmptyObjects bool) (common.Hash, er
12691272
if err := s.snaps.Update(root, parent, s.convertAccountSet(s.stateObjectsDestruct), s.accounts, s.storages); err != nil {
12701273
log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err)
12711274
}
1272-
// Keep 128 diff layers in the memory, persistent layer is 129th.
1275+
// Keep TriesInMemory diff layers in the memory, persistent layer is 129th.
12731276
// - head layer is paired with HEAD state
12741277
// - head-1 layer is paired with HEAD-1 state
12751278
// - head-127 layer(bottom-most diff layer) is paired with HEAD-127 state
1276-
if err := s.snaps.Cap(root, 128); err != nil {
1277-
log.Warn("Failed to cap snapshot tree", "root", root, "layers", 128, "err", err)
1279+
if err := s.snaps.Cap(root, TriesInMemory); err != nil {
1280+
log.Warn("Failed to cap snapshot tree", "root", root, "layers", TriesInMemory, "err", err)
12781281
}
12791282
}
12801283
s.SnapshotCommits += time.Since(start)

0 commit comments

Comments
 (0)