Skip to content

Commit 434dd5b

Browse files
committed
cmd, core, eth, light, trie: add trie read caching layer
1 parent 9a00060 commit 434dd5b

33 files changed

Lines changed: 1660 additions & 127 deletions

‎cmd/geth/main.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ var (
8989
utils.LightKDFFlag,
9090
utils.CacheFlag,
9191
utils.CacheDatabaseFlag,
92+
utils.CacheTrieFlag,
9293
utils.CacheGCFlag,
9394
utils.TrieCacheGenFlag,
9495
utils.ListenPortFlag,

‎cmd/geth/usage.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ var AppHelpFlagGroups = []flagGroup{
132132
Flags: []cli.Flag{
133133
utils.CacheFlag,
134134
utils.CacheDatabaseFlag,
135+
utils.CacheTrieFlag,
135136
utils.CacheGCFlag,
136137
utils.TrieCacheGenFlag,
137138
},

‎cmd/utils/flags.go‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,12 @@ var (
295295
CacheDatabaseFlag = cli.IntFlag{
296296
Name: "cache.database",
297297
Usage: "Percentage of cache memory allowance to use for database io",
298-
Value: 75,
298+
Value: 50,
299+
}
300+
CacheTrieFlag = cli.IntFlag{
301+
Name: "cache.trie",
302+
Usage: "Percentage of cache memory allowance to use for trie caching",
303+
Value: 25,
299304
}
300305
CacheGCFlag = cli.IntFlag{
301306
Name: "cache.gc",
@@ -1157,8 +1162,11 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
11571162
}
11581163
cfg.NoPruning = ctx.GlobalString(GCModeFlag.Name) == "archive"
11591164

1165+
if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheTrieFlag.Name) {
1166+
cfg.TrieCleanCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheTrieFlag.Name) / 100
1167+
}
11601168
if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) {
1161-
cfg.TrieCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
1169+
cfg.TrieDirtyCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
11621170
}
11631171
if ctx.GlobalIsSet(MinerNotifyFlag.Name) {
11641172
cfg.MinerNotify = strings.Split(ctx.GlobalString(MinerNotifyFlag.Name), ",")
@@ -1393,12 +1401,16 @@ func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chai
13931401
Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
13941402
}
13951403
cache := &core.CacheConfig{
1396-
Disabled: ctx.GlobalString(GCModeFlag.Name) == "archive",
1397-
TrieNodeLimit: eth.DefaultConfig.TrieCache,
1398-
TrieTimeLimit: eth.DefaultConfig.TrieTimeout,
1404+
Disabled: ctx.GlobalString(GCModeFlag.Name) == "archive",
1405+
TrieCleanLimit: eth.DefaultConfig.TrieCleanCache,
1406+
TrieDirtyLimit: eth.DefaultConfig.TrieDirtyCache,
1407+
TrieTimeLimit: eth.DefaultConfig.TrieTimeout,
1408+
}
1409+
if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheTrieFlag.Name) {
1410+
cache.TrieCleanLimit = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheTrieFlag.Name) / 100
13991411
}
14001412
if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) {
1401-
cache.TrieNodeLimit = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
1413+
cache.TrieDirtyLimit = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
14021414
}
14031415
vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)}
14041416
chain, err = core.NewBlockChain(chainDb, cache, config, engine, vmcfg, nil)

‎core/blockchain.go‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,10 @@ const (
6868
// CacheConfig contains the configuration values for the trie caching/pruning
6969
// that's resident in a blockchain.
7070
type CacheConfig struct {
71-
Disabled bool // Whether to disable trie write caching (archive node)
72-
TrieNodeLimit int // Memory limit (MB) at which to flush the current in-memory trie to disk
73-
TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
71+
Disabled bool // Whether to disable trie write caching (archive node)
72+
TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory
73+
TrieDirtyLimit int // Memory limit (MB) at which to start flushing dirty trie nodes to disk
74+
TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
7475
}
7576

7677
// BlockChain represents the canonical chain given a database with a genesis
@@ -140,8 +141,9 @@ type BlockChain struct {
140141
func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool) (*BlockChain, error) {
141142
if cacheConfig == nil {
142143
cacheConfig = &CacheConfig{
143-
TrieNodeLimit: 256,
144-
TrieTimeLimit: 5 * time.Minute,
144+
TrieCleanLimit: 256,
145+
TrieDirtyLimit: 256,
146+
TrieTimeLimit: 5 * time.Minute,
145147
}
146148
}
147149
bodyCache, _ := lru.New(bodyCacheLimit)
@@ -156,7 +158,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
156158
cacheConfig: cacheConfig,
157159
db: db,
158160
triegc: prque.New(nil),
159-
stateCache: state.NewDatabase(db),
161+
stateCache: state.NewDatabaseWithCache(db, cacheConfig.TrieCleanLimit),
160162
quit: make(chan struct{}),
161163
shouldPreserve: shouldPreserve,
162164
bodyCache: bodyCache,
@@ -393,6 +395,11 @@ func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
393395
return state.New(root, bc.stateCache)
394396
}
395397

398+
// StateCache returns the caching database underpinning the blockchain instance.
399+
func (bc *BlockChain) StateCache() state.Database {
400+
return bc.stateCache
401+
}
402+
396403
// Reset purges the entire blockchain, restoring it to its genesis state.
397404
func (bc *BlockChain) Reset() error {
398405
return bc.ResetWithGenesisBlock(bc.genesisBlock)
@@ -938,7 +945,7 @@ func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.
938945
// If we exceeded our memory allowance, flush matured singleton nodes to disk
939946
var (
940947
nodes, imgs = triedb.Size()
941-
limit = common.StorageSize(bc.cacheConfig.TrieNodeLimit) * 1024 * 1024
948+
limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024
942949
)
943950
if nodes > limit || imgs > 4*1024*1024 {
944951
triedb.Cap(limit - ethdb.IdealBatchSize)

‎core/state/database.go‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,19 @@ type Trie interface {
7272
}
7373

7474
// NewDatabase creates a backing store for state. The returned database is safe for
75-
// concurrent use and retains cached trie nodes in memory. The pool is an optional
76-
// intermediate trie-node memory pool between the low level storage layer and the
77-
// high level trie abstraction.
75+
// concurrent use and retains a few recent expanded trie nodes in memory. To keep
76+
// more historical state in memory, use the NewDatabaseWithCache constructor.
7877
func NewDatabase(db ethdb.Database) Database {
78+
return NewDatabaseWithCache(db, 0)
79+
}
80+
81+
// NewDatabase creates a backing store for state. The returned database is safe for
82+
// concurrent use and retains both a few recent expanded trie nodes in memory, as
83+
// well as a lot of collapsed RLP trie nodes in a large memory cache.
84+
func NewDatabaseWithCache(db ethdb.Database, cache int) Database {
7985
csc, _ := lru.New(codeSizeCacheSize)
8086
return &cachingDB{
81-
db: trie.NewDatabase(db),
87+
db: trie.NewDatabaseWithCache(db, cache),
8288
codeSizeCache: csc,
8389
}
8490
}

‎eth/api.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -444,16 +444,16 @@ func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Bloc
444444
if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
445445
return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
446446
}
447+
triedb := api.eth.BlockChain().StateCache().TrieDB()
447448

448-
oldTrie, err := trie.NewSecure(startBlock.Root(), trie.NewDatabase(api.eth.chainDb), 0)
449+
oldTrie, err := trie.NewSecure(startBlock.Root(), triedb, 0)
449450
if err != nil {
450451
return nil, err
451452
}
452-
newTrie, err := trie.NewSecure(endBlock.Root(), trie.NewDatabase(api.eth.chainDb), 0)
453+
newTrie, err := trie.NewSecure(endBlock.Root(), triedb, 0)
453454
if err != nil {
454455
return nil, err
455456
}
456-
457457
diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}))
458458
iter := trie.NewIterator(diff)
459459

‎eth/api_tracer.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ func (api *PrivateDebugAPI) traceChain(ctx context.Context, start, end *types.Bl
138138

139139
// Ensure we have a valid starting state before doing any work
140140
origin := start.NumberU64()
141-
database := state.NewDatabase(api.eth.ChainDb())
141+
database := state.NewDatabaseWithCache(api.eth.ChainDb(), 16) // Chain tracing will probably start at genesis
142142

143143
if number := start.NumberU64(); number > 0 {
144144
start = api.eth.blockchain.GetBlock(start.ParentHash(), start.NumberU64()-1)
@@ -492,7 +492,7 @@ func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*
492492
}
493493
// Otherwise try to reexec blocks until we find a state or reach our limit
494494
origin := block.NumberU64()
495-
database := state.NewDatabase(api.eth.ChainDb())
495+
database := state.NewDatabaseWithCache(api.eth.ChainDb(), 16)
496496

497497
for i := uint64(0); i < reexec; i++ {
498498
block = api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)

‎eth/backend.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
154154
EWASMInterpreter: config.EWASMInterpreter,
155155
EVMInterpreter: config.EVMInterpreter,
156156
}
157-
cacheConfig = &core.CacheConfig{Disabled: config.NoPruning, TrieNodeLimit: config.TrieCache, TrieTimeLimit: config.TrieTimeout}
157+
cacheConfig = &core.CacheConfig{Disabled: config.NoPruning, TrieCleanLimit: config.TrieCleanCache, TrieDirtyLimit: config.TrieDirtyCache, TrieTimeLimit: config.TrieTimeout}
158158
)
159159
eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, eth.chainConfig, eth.engine, vmConfig, eth.shouldPreserve)
160160
if err != nil {

‎eth/config.go‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,16 @@ var DefaultConfig = Config{
4343
DatasetsInMem: 1,
4444
DatasetsOnDisk: 2,
4545
},
46-
NetworkId: 1,
47-
LightPeers: 100,
48-
DatabaseCache: 768,
49-
TrieCache: 256,
50-
TrieTimeout: 60 * time.Minute,
51-
MinerGasFloor: 8000000,
52-
MinerGasCeil: 8000000,
53-
MinerGasPrice: big.NewInt(params.GWei),
54-
MinerRecommit: 3 * time.Second,
46+
NetworkId: 1,
47+
LightPeers: 100,
48+
DatabaseCache: 512,
49+
TrieCleanCache: 256,
50+
TrieDirtyCache: 256,
51+
TrieTimeout: 60 * time.Minute,
52+
MinerGasFloor: 8000000,
53+
MinerGasCeil: 8000000,
54+
MinerGasPrice: big.NewInt(params.GWei),
55+
MinerRecommit: 3 * time.Second,
5556

5657
TxPool: core.DefaultTxPoolConfig,
5758
GPO: gasprice.Config{
@@ -94,7 +95,8 @@ type Config struct {
9495
SkipBcVersionCheck bool `toml:"-"`
9596
DatabaseHandles int `toml:"-"`
9697
DatabaseCache int
97-
TrieCache int
98+
TrieCleanCache int
99+
TrieDirtyCache int
98100
TrieTimeout time.Duration
99101

100102
// Mining-related options

‎eth/gen_config.go‎

Lines changed: 23 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)