Skip to content

Commit 940e317

Browse files
committed
core: fix pruner panic when importing low-diff-large-sidechain
1 parent da1efda commit 940e317

3 files changed

Lines changed: 44 additions & 86 deletions

File tree

‎core/blockchain.go‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -979,20 +979,26 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.
979979
triedb.Cap(limit - ethdb.IdealBatchSize)
980980
}
981981
// Find the next state trie we need to commit
982-
header := bc.GetHeaderByNumber(current - triesInMemory)
983-
chosen := header.Number.Uint64()
982+
chosen := current - triesInMemory
984983

985984
// If we exceeded out time allowance, flush an entire trie to disk
986985
if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
987-
// If we're exceeding limits but haven't reached a large enough memory gap,
988-
// warn the user that the system is becoming unstable.
989-
if chosen < lastWrite+triesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
990-
log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/triesInMemory)
986+
// If the header is missing (canonical chain behind), we're reorging a low
987+
// diff sidechain. Suspend committing until this operation is completed.
988+
header := bc.GetHeaderByNumber(chosen)
989+
if header == nil {
990+
log.Warn("Reorg in progress, trie commit postponed", "number", chosen)
991+
} else {
992+
// If we're exceeding limits but haven't reached a large enough memory gap,
993+
// warn the user that the system is becoming unstable.
994+
if chosen < lastWrite+triesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
995+
log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/triesInMemory)
996+
}
997+
// Flush an entire trie and restart the counters
998+
triedb.Commit(header.Root, true)
999+
lastWrite = chosen
1000+
bc.gcproc = 0
9911001
}
992-
// Flush an entire trie and restart the counters
993-
triedb.Commit(header.Root, true)
994-
lastWrite = chosen
995-
bc.gcproc = 0
9961002
}
9971003
// Garbage collect anything below our required write retention
9981004
for !bc.triegc.Empty() {
@@ -1324,7 +1330,7 @@ func (bc *BlockChain) insertSidechain(block *types.Block, it *insertIterator) (i
13241330
if err := bc.WriteBlockWithoutState(block, externTd); err != nil {
13251331
return it.index, nil, nil, err
13261332
}
1327-
log.Debug("Inserted sidechain block", "number", block.Number(), "hash", block.Hash(),
1333+
log.Debug("Injected sidechain block", "number", block.Number(), "hash", block.Hash(),
13281334
"diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
13291335
"txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
13301336
"root", block.Root())

‎core/blockchain_test.go‎

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1487,16 +1487,22 @@ func BenchmarkBlockChain_1x1000Executions(b *testing.B) {
14871487
// Tests that importing a very large side fork, which is larger than the canon chain,
14881488
// but where the difficulty per block is kept low: this means that it will not
14891489
// overtake the 'canon' chain until after it's passed canon by about 200 blocks.
1490-
func TestLargeOldSidechainWithALowTdChain(t *testing.T) {
1491-
1490+
//
1491+
// Details at:
1492+
// - https://github.com/ethereum/go-ethereum/issues/18977
1493+
// - https://github.com/ethereum/go-ethereum/pull/18988
1494+
func TestLowDiffLongChain(t *testing.T) {
14921495
// Generate a canonical chain to act as the main dataset
14931496
engine := ethash.NewFaker()
1494-
14951497
db := ethdb.NewMemDatabase()
14961498
genesis := new(Genesis).MustCommit(db)
1497-
// We must use a pretty long chain to ensure that the fork
1498-
// doesn't overtake us until after at least 128 blocks post tip
1499-
blocks, _ := generateChain(params.TestChainConfig, genesis, engine, db, 6*triesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) }, makeHeaderWithLargeDifficulty)
1499+
1500+
// We must use a pretty long chain to ensure that the fork doesn't overtake us
1501+
// until after at least 128 blocks post tip
1502+
blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 6*triesInMemory, func(i int, b *BlockGen) {
1503+
b.SetCoinbase(common.Address{1})
1504+
b.OffsetTime(-9)
1505+
})
15001506

15011507
// Import the canonical chain
15021508
diskdb := ethdb.NewMemDatabase()
@@ -1506,19 +1512,14 @@ func TestLargeOldSidechainWithALowTdChain(t *testing.T) {
15061512
if err != nil {
15071513
t.Fatalf("failed to create tester chain: %v", err)
15081514
}
1509-
for i := 0; i < len(blocks); i++ {
1510-
if _, err := chain.InsertChain(blocks[i : i+1]); err != nil {
1511-
t.Fatalf("block %d: failed to insert into chain: %v", i, err)
1512-
}
1515+
if n, err := chain.InsertChain(blocks); err != nil {
1516+
t.Fatalf("block %d: failed to insert into chain: %v", n, err)
15131517
}
1514-
// Dereference all the recent tries and ensure no past trie is left in
1515-
for i := 0; i < triesInMemory; i++ {
1516-
chain.stateCache.TrieDB().Dereference(blocks[len(blocks)-1-i].Root())
1517-
}
1518-
15191518
// Generate fork chain, starting from an early block
15201519
parent := blocks[10]
1521-
fork, _ := generateChain(params.TestChainConfig, parent, engine, db, 256+6*triesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) }, makeHeaderWithSmallDifficulty)
1520+
fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 8*triesInMemory, func(i int, b *BlockGen) {
1521+
b.SetCoinbase(common.Address{2})
1522+
})
15221523

15231524
// And now import the fork
15241525
if i, err := chain.InsertChain(fork); err != nil {
@@ -1528,6 +1529,12 @@ func TestLargeOldSidechainWithALowTdChain(t *testing.T) {
15281529
if got := fork[len(fork)-1].Hash(); got != head.Hash() {
15291530
t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
15301531
}
1531-
td := chain.GetTd(head.Hash(), head.NumberU64())
1532-
fmt.Printf("td %v", td)
1532+
// Sanity check that all the canonical numbers are present
1533+
header := chain.CurrentHeader()
1534+
for number := head.NumberU64(); number > 0; number-- {
1535+
if hash := chain.GetHeaderByNumber(number).Hash(); hash != header.Hash() {
1536+
t.Fatalf("header %d: canonical hash mismatch: have %x, want %x", number, hash, header.Hash())
1537+
}
1538+
header = chain.GetHeader(header.ParentHash, number-1)
1539+
}
15331540
}

‎core/chain_makers.go‎

Lines changed: 2 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,6 @@ type BlockGen struct {
4848
engine consensus.Engine
4949
}
5050

51-
type headerGenFn func(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header
52-
5351
// SetCoinbase sets the coinbase of the generated block.
5452
// It can be called at most once.
5553
func (b *BlockGen) SetCoinbase(addr common.Address) {
@@ -151,7 +149,7 @@ func (b *BlockGen) PrevBlock(index int) *types.Block {
151149
// associated difficulty. It's useful to test scenarios where forking is not
152150
// tied to chain length directly.
153151
func (b *BlockGen) OffsetTime(seconds int64) {
154-
b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds))
152+
b.header.Time.Add(b.header.Time, big.NewInt(seconds))
155153
if b.header.Time.Cmp(b.parent.Header().Time) <= 0 {
156154
panic("block time out of range")
157155
}
@@ -172,19 +170,14 @@ func (b *BlockGen) OffsetTime(seconds int64) {
172170
// values. Inserting them into BlockChain requires use of FakePow or
173171
// a similar non-validating proof of work implementation.
174172
func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
175-
return generateChain(config, parent, engine, db, n, gen, makeHeader)
176-
}
177-
178-
func generateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen), headerGen headerGenFn) ([]*types.Block, []types.Receipts) {
179173
if config == nil {
180174
config = params.TestChainConfig
181175
}
182176
blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
183177
chainreader := &fakeChainReader{config: config}
184178
genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) {
185179
b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine}
186-
//b.header = makeHeader(chainreader, parent, statedb, b.engine)
187-
b.header = headerGen(chainreader, parent, statedb, b.engine)
180+
b.header = makeHeader(chainreader, parent, statedb, b.engine)
188181

189182
// Mutate the state and block according to any hard-fork specs
190183
if daoBlock := config.DAOForkBlock; daoBlock != nil {
@@ -255,54 +248,6 @@ func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.S
255248
}
256249
}
257250

258-
func makeHeaderWithLargeDifficulty(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
259-
var time *big.Int
260-
if parent.Time() == nil {
261-
time = big.NewInt(1)
262-
} else {
263-
time = new(big.Int).Add(parent.Time(), big.NewInt(1)) // block time is fixed at 10 seconds
264-
}
265-
266-
return &types.Header{
267-
Root: state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())),
268-
ParentHash: parent.Hash(),
269-
Coinbase: parent.Coinbase(),
270-
Difficulty: engine.CalcDifficulty(chain, time.Uint64(), &types.Header{
271-
Number: parent.Number(),
272-
Time: new(big.Int).Sub(time, big.NewInt(1)),
273-
Difficulty: parent.Difficulty(),
274-
UncleHash: parent.UncleHash(),
275-
}),
276-
GasLimit: CalcGasLimit(parent, parent.GasLimit(), parent.GasLimit()),
277-
Number: new(big.Int).Add(parent.Number(), common.Big1),
278-
Time: time,
279-
}
280-
}
281-
282-
func makeHeaderWithSmallDifficulty(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
283-
var time *big.Int
284-
if parent.Time() == nil {
285-
time = big.NewInt(30)
286-
} else {
287-
time = new(big.Int).Add(parent.Time(), big.NewInt(30)) // block time is fixed at 10 seconds
288-
}
289-
290-
return &types.Header{
291-
Root: state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())),
292-
ParentHash: parent.Hash(),
293-
Coinbase: parent.Coinbase(),
294-
Difficulty: engine.CalcDifficulty(chain, time.Uint64(), &types.Header{
295-
Number: parent.Number(),
296-
Time: new(big.Int).Sub(time, big.NewInt(30)),
297-
Difficulty: parent.Difficulty(),
298-
UncleHash: parent.UncleHash(),
299-
}),
300-
GasLimit: CalcGasLimit(parent, parent.GasLimit(), parent.GasLimit()),
301-
Number: new(big.Int).Add(parent.Number(), common.Big1),
302-
Time: time,
303-
}
304-
}
305-
306251
// makeHeaderChain creates a deterministic chain of headers rooted at parent.
307252
func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header {
308253
blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)

0 commit comments

Comments
 (0)