@@ -116,6 +116,8 @@ const (
116116// that's resident in a blockchain.
117117type CacheConfig struct {
118118 TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory
119+ TrieCleanJournal string // Disk journal for saving clean cache entries.
120+ TrieCleanRejournal time.Duration // Time interval to dump clean cache to disk periodically
119121 TrieCleanNoPrefetch bool // Whether to disable heuristic state prefetching for followup blocks
120122 TrieDirtyLimit int // Memory limit (MB) at which to start flushing dirty trie nodes to disk
121123 TrieDirtyDisabled bool // Whether to disable trie write caching and GC altogether (archive node)
@@ -220,7 +222,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
220222 cacheConfig : cacheConfig ,
221223 db : db ,
222224 triegc : prque .New (nil ),
223- stateCache : state .NewDatabaseWithCache (db , cacheConfig .TrieCleanLimit ),
225+ stateCache : state .NewDatabaseWithCache (db , cacheConfig .TrieCleanLimit , cacheConfig . TrieCleanJournal ),
224226 quit : make (chan struct {}),
225227 shouldPreserve : shouldPreserve ,
226228 bodyCache : bodyCache ,
@@ -328,6 +330,19 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
328330 bc .txLookupLimit = * txLookupLimit
329331 go bc .maintainTxIndex (txIndexBlock )
330332 }
333+ // If periodic cache journal is required, spin it up.
334+ if bc .cacheConfig .TrieCleanRejournal > 0 {
335+ if bc .cacheConfig .TrieCleanRejournal < time .Minute {
336+ log .Warn ("Sanitizing invalid trie cache journal time" , "provided" , bc .cacheConfig .TrieCleanRejournal , "updated" , time .Minute )
337+ bc .cacheConfig .TrieCleanRejournal = time .Minute
338+ }
339+ triedb := bc .stateCache .TrieDB ()
340+ bc .wg .Add (1 )
341+ go func () {
342+ defer bc .wg .Done ()
343+ triedb .SaveCachePeriodically (bc .cacheConfig .TrieCleanJournal , bc .cacheConfig .TrieCleanRejournal , bc .quit )
344+ }()
345+ }
331346 return bc , nil
332347}
333348
@@ -919,6 +934,12 @@ func (bc *BlockChain) Stop() {
919934 log .Error ("Dangling trie nodes after full cleanup" )
920935 }
921936 }
937+ // Ensure all live cached entries be saved into disk, so that we can skip
938+ // cache warmup when node restarts.
939+ if bc .cacheConfig .TrieCleanJournal != "" {
940+ triedb := bc .stateCache .TrieDB ()
941+ triedb .SaveCache (bc .cacheConfig .TrieCleanJournal )
942+ }
922943 log .Info ("Blockchain stopped" )
923944}
924945
0 commit comments