Skip to content

Commit 55599ee

Browse files
karalabefjl
authored andcommitted
core, trie: intermediate mempool between trie and database (#15857)
This commit reduces database I/O by not writing every state trie to disk.
1 parent 5933628 commit 55599ee

69 files changed

Lines changed: 1953 additions & 1159 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎accounts/abi/bind/backends/simulated.go‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ func NewSimulatedBackend(alloc core.GenesisAlloc) *SimulatedBackend {
6868
database, _ := ethdb.NewMemDatabase()
6969
genesis := core.Genesis{Config: params.AllEthashProtocolChanges, Alloc: alloc}
7070
genesis.MustCommit(database)
71-
blockchain, _ := core.NewBlockChain(database, genesis.Config, ethash.NewFaker(), vm.Config{})
71+
blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{})
7272

7373
backend := &SimulatedBackend{
7474
database: database,
@@ -102,8 +102,10 @@ func (b *SimulatedBackend) Rollback() {
102102

103103
func (b *SimulatedBackend) rollback() {
104104
blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {})
105+
statedb, _ := b.blockchain.State()
106+
105107
b.pendingBlock = blocks[0]
106-
b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database))
108+
b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
107109
}
108110

109111
// CodeAt returns the code associated with a certain account in the blockchain.
@@ -309,8 +311,10 @@ func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transa
309311
}
310312
block.AddTx(tx)
311313
})
314+
statedb, _ := b.blockchain.State()
315+
312316
b.pendingBlock = blocks[0]
313-
b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database))
317+
b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
314318
return nil
315319
}
316320

@@ -386,8 +390,10 @@ func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
386390
}
387391
block.OffsetTime(int64(adjustment.Seconds()))
388392
})
393+
statedb, _ := b.blockchain.State()
394+
389395
b.pendingBlock = blocks[0]
390-
b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database))
396+
b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
391397

392398
return nil
393399
}

‎cmd/evm/runner.go‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,9 @@ func runCmd(ctx *cli.Context) error {
9696
}
9797
if ctx.GlobalString(GenesisFlag.Name) != "" {
9898
gen := readGenesis(ctx.GlobalString(GenesisFlag.Name))
99-
_, statedb = gen.ToBlock()
99+
db, _ := ethdb.NewMemDatabase()
100+
genesis := gen.ToBlock(db)
101+
statedb, _ = state.New(genesis.Root(), state.NewDatabase(db))
100102
chainConfig = gen.Config
101103
} else {
102104
db, _ := ethdb.NewMemDatabase()

‎cmd/geth/chaincmd.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ func importChain(ctx *cli.Context) error {
202202

203203
if len(ctx.Args()) == 1 {
204204
if err := utils.ImportChain(chain, ctx.Args().First()); err != nil {
205-
utils.Fatalf("Import error: %v", err)
205+
log.Error("Import error", "err", err)
206206
}
207207
} else {
208208
for _, arg := range ctx.Args() {
@@ -211,7 +211,7 @@ func importChain(ctx *cli.Context) error {
211211
}
212212
}
213213
}
214-
214+
chain.Stop()
215215
fmt.Printf("Import done in %v.\n\n", time.Since(start))
216216

217217
// Output pre-compaction stats mostly to see the import trashing

‎cmd/geth/main.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,13 @@ var (
8585
utils.FastSyncFlag,
8686
utils.LightModeFlag,
8787
utils.SyncModeFlag,
88+
utils.GCModeFlag,
8889
utils.LightServFlag,
8990
utils.LightPeersFlag,
9091
utils.LightKDFFlag,
9192
utils.CacheFlag,
93+
utils.CacheDatabaseFlag,
94+
utils.CacheGCFlag,
9295
utils.TrieCacheGenFlag,
9396
utils.ListenPortFlag,
9497
utils.MaxPeersFlag,

‎cmd/geth/usage.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,11 @@ import (
2222
"io"
2323
"sort"
2424

25+
"strings"
26+
2527
"github.com/ethereum/go-ethereum/cmd/utils"
2628
"github.com/ethereum/go-ethereum/internal/debug"
2729
"gopkg.in/urfave/cli.v1"
28-
"strings"
2930
)
3031

3132
// AppHelpTemplate is the test template for the default, global app help topic.
@@ -74,6 +75,7 @@ var AppHelpFlagGroups = []flagGroup{
7475
utils.TestnetFlag,
7576
utils.RinkebyFlag,
7677
utils.SyncModeFlag,
78+
utils.GCModeFlag,
7779
utils.EthStatsURLFlag,
7880
utils.IdentityFlag,
7981
utils.LightServFlag,
@@ -127,6 +129,8 @@ var AppHelpFlagGroups = []flagGroup{
127129
Name: "PERFORMANCE TUNING",
128130
Flags: []cli.Flag{
129131
utils.CacheFlag,
132+
utils.CacheDatabaseFlag,
133+
utils.CacheGCFlag,
130134
utils.TrieCacheGenFlag,
131135
},
132136
},

‎cmd/utils/cmd.go‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,6 @@ func ImportChain(chain *core.BlockChain, fn string) error {
116116
return err
117117
}
118118
}
119-
120119
stream := rlp.NewStream(reader, 0)
121120

122121
// Run actual the import.
@@ -150,25 +149,34 @@ func ImportChain(chain *core.BlockChain, fn string) error {
150149
if checkInterrupt() {
151150
return fmt.Errorf("interrupted")
152151
}
153-
if hasAllBlocks(chain, blocks[:i]) {
152+
missing := missingBlocks(chain, blocks[:i])
153+
if len(missing) == 0 {
154154
log.Info("Skipping batch as all blocks present", "batch", batch, "first", blocks[0].Hash(), "last", blocks[i-1].Hash())
155155
continue
156156
}
157-
158-
if _, err := chain.InsertChain(blocks[:i]); err != nil {
157+
if _, err := chain.InsertChain(missing); err != nil {
159158
return fmt.Errorf("invalid block %d: %v", n, err)
160159
}
161160
}
162161
return nil
163162
}
164163

165-
func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
166-
for _, b := range bs {
167-
if !chain.HasBlock(b.Hash(), b.NumberU64()) {
168-
return false
164+
func missingBlocks(chain *core.BlockChain, blocks []*types.Block) []*types.Block {
165+
head := chain.CurrentBlock()
166+
for i, block := range blocks {
167+
// If we're behind the chain head, only check block, state is available at head
168+
if head.NumberU64() > block.NumberU64() {
169+
if !chain.HasBlock(block.Hash(), block.NumberU64()) {
170+
return blocks[i:]
171+
}
172+
continue
173+
}
174+
// If we're above the chain head, state availability is a must
175+
if !chain.HasBlockAndState(block.Hash(), block.NumberU64()) {
176+
return blocks[i:]
169177
}
170178
}
171-
return true
179+
return nil
172180
}
173181

174182
func ExportChain(blockchain *core.BlockChain, fn string) error {

‎cmd/utils/flags.go‎

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,11 @@ var (
170170
Usage: `Blockchain sync mode ("fast", "full", or "light")`,
171171
Value: &defaultSyncMode,
172172
}
173-
173+
GCModeFlag = cli.StringFlag{
174+
Name: "gcmode",
175+
Usage: `Blockchain garbage collection mode ("full", "archive")`,
176+
Value: "full",
177+
}
174178
LightServFlag = cli.IntFlag{
175179
Name: "lightserv",
176180
Usage: "Maximum percentage of time allowed for serving LES requests (0-90)",
@@ -293,8 +297,18 @@ var (
293297
// Performance tuning settings
294298
CacheFlag = cli.IntFlag{
295299
Name: "cache",
296-
Usage: "Megabytes of memory allocated to internal caching (min 16MB / database forced)",
297-
Value: 128,
300+
Usage: "Megabytes of memory allocated to internal caching",
301+
Value: 1024,
302+
}
303+
CacheDatabaseFlag = cli.IntFlag{
304+
Name: "cache.database",
305+
Usage: "Percentage of cache memory allowance to use for database io",
306+
Value: 75,
307+
}
308+
CacheGCFlag = cli.IntFlag{
309+
Name: "cache.gc",
310+
Usage: "Percentage of cache memory allowance to use for trie pruning",
311+
Value: 25,
298312
}
299313
TrieCacheGenFlag = cli.IntFlag{
300314
Name: "trie-cache-gens",
@@ -1021,11 +1035,19 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
10211035
cfg.NetworkId = ctx.GlobalUint64(NetworkIdFlag.Name)
10221036
}
10231037

1024-
if ctx.GlobalIsSet(CacheFlag.Name) {
1025-
cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name)
1038+
if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheDatabaseFlag.Name) {
1039+
cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100
10261040
}
10271041
cfg.DatabaseHandles = makeDatabaseHandles()
10281042

1043+
if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
1044+
Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
1045+
}
1046+
cfg.NoPruning = ctx.GlobalString(GCModeFlag.Name) == "archive"
1047+
1048+
if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) {
1049+
cfg.TrieCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
1050+
}
10291051
if ctx.GlobalIsSet(MinerThreadsFlag.Name) {
10301052
cfg.MinerThreads = ctx.GlobalInt(MinerThreadsFlag.Name)
10311053
}
@@ -1157,7 +1179,7 @@ func SetupNetwork(ctx *cli.Context) {
11571179
// MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
11581180
func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
11591181
var (
1160-
cache = ctx.GlobalInt(CacheFlag.Name)
1182+
cache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100
11611183
handles = makeDatabaseHandles()
11621184
)
11631185
name := "chaindata"
@@ -1209,8 +1231,19 @@ func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chai
12091231
})
12101232
}
12111233
}
1234+
if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
1235+
Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
1236+
}
1237+
cache := &core.CacheConfig{
1238+
Disabled: ctx.GlobalString(GCModeFlag.Name) == "archive",
1239+
TrieNodeLimit: eth.DefaultConfig.TrieCache,
1240+
TrieTimeLimit: eth.DefaultConfig.TrieTimeout,
1241+
}
1242+
if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) {
1243+
cache.TrieNodeLimit = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
1244+
}
12121245
vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)}
1213-
chain, err = core.NewBlockChain(chainDb, config, engine, vmcfg)
1246+
chain, err = core.NewBlockChain(chainDb, cache, config, engine, vmcfg)
12141247
if err != nil {
12151248
Fatalf("Can't create BlockChain: %v", err)
12161249
}

‎common/size.go‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,29 @@ import (
2020
"fmt"
2121
)
2222

23+
// StorageSize is a wrapper around a float value that supports user friendly
24+
// formatting.
2325
type StorageSize float64
2426

25-
func (self StorageSize) String() string {
26-
if self > 1000000 {
27-
return fmt.Sprintf("%.2f mB", self/1000000)
28-
} else if self > 1000 {
29-
return fmt.Sprintf("%.2f kB", self/1000)
27+
// String implements the stringer interface.
28+
func (s StorageSize) String() string {
29+
if s > 1000000 {
30+
return fmt.Sprintf("%.2f mB", s/1000000)
31+
} else if s > 1000 {
32+
return fmt.Sprintf("%.2f kB", s/1000)
3033
} else {
31-
return fmt.Sprintf("%.2f B", self)
34+
return fmt.Sprintf("%.2f B", s)
3235
}
3336
}
3437

35-
func (self StorageSize) Int64() int64 {
36-
return int64(self)
38+
// TerminalString implements log.TerminalStringer, formatting a string for console
39+
// output during logging.
40+
func (s StorageSize) TerminalString() string {
41+
if s > 1000000 {
42+
return fmt.Sprintf("%.2fmB", s/1000000)
43+
} else if s > 1000 {
44+
return fmt.Sprintf("%.2fkB", s/1000)
45+
} else {
46+
return fmt.Sprintf("%.2fB", s)
47+
}
3748
}

‎consensus/errors.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ var (
2323
// that is unknown.
2424
ErrUnknownAncestor = errors.New("unknown ancestor")
2525

26+
// ErrPrunedAncestor is returned when validating a block requires an ancestor
27+
// that is known, but the state of which is not available.
28+
ErrPrunedAncestor = errors.New("pruned ancestor")
29+
2630
// ErrFutureBlock is returned when a block's timestamp is in the future according
2731
// to the current node.
2832
ErrFutureBlock = errors.New("block in the future")

‎core/bench_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) {
173173

174174
// Time the insertion of the new chain.
175175
// State and blocks are stored in the same DB.
176-
chainman, _ := NewBlockChain(db, gspec.Config, ethash.NewFaker(), vm.Config{})
176+
chainman, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
177177
defer chainman.Stop()
178178
b.ReportAllocs()
179179
b.ResetTimer()
@@ -283,7 +283,7 @@ func benchReadChain(b *testing.B, full bool, count uint64) {
283283
if err != nil {
284284
b.Fatalf("error opening database at %v: %v", dir, err)
285285
}
286-
chain, err := NewBlockChain(db, params.TestChainConfig, ethash.NewFaker(), vm.Config{})
286+
chain, err := NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{})
287287
if err != nil {
288288
b.Fatalf("error creating chain: %v", err)
289289
}

0 commit comments

Comments
 (0)