Skip to content

Commit 8577b5b

Browse files
holimankaralabe
authored andcommitted
core: more tests for sidechain import, fixes #19105 (#19113)
* blockchain: more tests for sidechain import, fixes #19105 * core/blockchain: rework import of pruned canon blocks and canon-prepended sidechains * core/blockchain: minor clarity change * core/blockchain: remove unused method
1 parent 628a0bd commit 8577b5b

2 files changed

Lines changed: 115 additions & 20 deletions

File tree

‎core/blockchain.go‎

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,15 +1084,21 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
10841084
if len(chain) == 0 {
10851085
return 0, nil
10861086
}
1087+
// Remove already known canon-blocks
1088+
var (
1089+
block, prev *types.Block
1090+
)
10871091
// Do a sanity check that the provided chain is actually ordered and linked
10881092
for i := 1; i < len(chain); i++ {
1089-
if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() {
1093+
block = chain[i]
1094+
prev = chain[i-1]
1095+
if block.NumberU64() != prev.NumberU64()+1 || block.ParentHash() != prev.Hash() {
10901096
// Chain broke ancestry, log a message (programming error) and skip insertion
1091-
log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(),
1092-
"parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash())
1097+
log.Error("Non contiguous block insert", "number", block.Number(), "hash", block.Hash(),
1098+
"parent", block.ParentHash(), "prevnumber", prev.Number(), "prevhash", prev.Hash())
10931099

1094-
return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].NumberU64(),
1095-
chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4])
1100+
return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, prev.NumberU64(),
1101+
prev.Hash().Bytes()[:4], i, block.NumberU64(), block.Hash().Bytes()[:4], block.ParentHash().Bytes()[:4])
10961102
}
10971103
}
10981104
// Pre-checks passed, start the full block imports
@@ -1146,6 +1152,22 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []
11461152
it := newInsertIterator(chain, results, bc.Validator())
11471153

11481154
block, err := it.next()
1155+
1156+
// Left-trim all the known blocks
1157+
if err == ErrKnownBlock {
1158+
// First block (and state) is known
1159+
// 1. We did a roll-back, and should now do a re-import
1160+
// 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
1161+
// from the canonical chain, which has not been verified.
1162+
// Skip all known blocks that are behind us
1163+
current := bc.CurrentBlock().NumberU64()
1164+
for block != nil && err == ErrKnownBlock && current >= block.NumberU64() {
1165+
stats.ignored++
1166+
block, err = it.next()
1167+
}
1168+
// Falls through to the block import
1169+
}
1170+
11491171
switch {
11501172
// First block is pruned, insert as sidechain and reorg only if TD grows enough
11511173
case err == consensus.ErrPrunedAncestor:
@@ -1165,20 +1187,6 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []
11651187
// If there are any still remaining, mark as ignored
11661188
return it.index, events, coalescedLogs, err
11671189

1168-
// First block (and state) is known
1169-
// 1. We did a roll-back, and should now do a re-import
1170-
// 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
1171-
// from the canonical chain, which has not been verified.
1172-
case err == ErrKnownBlock:
1173-
// Skip all known blocks that behind us
1174-
current := bc.CurrentBlock().NumberU64()
1175-
1176-
for block != nil && err == ErrKnownBlock && current >= block.NumberU64() {
1177-
stats.ignored++
1178-
block, err = it.next()
1179-
}
1180-
// Falls through to the block import
1181-
11821190
// Some other error occurred, abort
11831191
case err != nil:
11841192
stats.ignored += len(it.chain)
@@ -1304,7 +1312,12 @@ func (bc *BlockChain) insertSidechain(block *types.Block, it *insertIterator) (i
13041312
for ; block != nil && (err == consensus.ErrPrunedAncestor); block, err = it.next() {
13051313
// Check the canonical state root for that number
13061314
if number := block.NumberU64(); current.NumberU64() >= number {
1307-
if canonical := bc.GetBlockByNumber(number); canonical != nil && canonical.Root() == block.Root() {
1315+
canonical := bc.GetBlockByNumber(number)
1316+
if canonical != nil && canonical.Hash() == block.Hash() {
1317+
// Not a sidechain block, this is a re-import of a canon block which has it's state pruned
1318+
continue
1319+
}
1320+
if canonical != nil && canonical.Root() == block.Root() {
13081321
// This is most likely a shadow-state attack. When a fork is imported into the
13091322
// database, and it eventually reaches a block height which is not pruned, we
13101323
// just found that the state already exist! This means that the sidechain block

‎core/blockchain_test.go‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,3 +1521,85 @@ func TestLowDiffLongChain(t *testing.T) {
15211521
header = chain.GetHeader(header.ParentHash, number-1)
15221522
}
15231523
}
1524+
1525+
// Tests that importing a sidechain (S), where
1526+
// - S is sidechain, containing blocks [Sn...Sm]
1527+
// - C is canon chain, containing blocks [G..Cn..Cm]
1528+
// - A common ancestor is placed at prune-point + blocksBetweenCommonAncestorAndPruneblock
1529+
// - The sidechain S is prepended with numCanonBlocksInSidechain blocks from the canon chain
1530+
func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommonAncestorAndPruneblock int) {
1531+
1532+
// Generate a canonical chain to act as the main dataset
1533+
engine := ethash.NewFaker()
1534+
db := ethdb.NewMemDatabase()
1535+
genesis := new(Genesis).MustCommit(db)
1536+
1537+
// Generate and import the canonical chain
1538+
blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2*triesInMemory, nil)
1539+
diskdb := ethdb.NewMemDatabase()
1540+
new(Genesis).MustCommit(diskdb)
1541+
chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
1542+
if err != nil {
1543+
t.Fatalf("failed to create tester chain: %v", err)
1544+
}
1545+
if n, err := chain.InsertChain(blocks); err != nil {
1546+
t.Fatalf("block %d: failed to insert into chain: %v", n, err)
1547+
}
1548+
1549+
lastPrunedIndex := len(blocks) - triesInMemory - 1
1550+
lastPrunedBlock := blocks[lastPrunedIndex]
1551+
firstNonPrunedBlock := blocks[len(blocks)-triesInMemory]
1552+
1553+
// Verify pruning of lastPrunedBlock
1554+
if chain.HasBlockAndState(lastPrunedBlock.Hash(), lastPrunedBlock.NumberU64()) {
1555+
t.Errorf("Block %d not pruned", lastPrunedBlock.NumberU64())
1556+
}
1557+
// Verify firstNonPrunedBlock is not pruned
1558+
if !chain.HasBlockAndState(firstNonPrunedBlock.Hash(), firstNonPrunedBlock.NumberU64()) {
1559+
t.Errorf("Block %d pruned", firstNonPrunedBlock.NumberU64())
1560+
}
1561+
// Generate the sidechain
1562+
// First block should be a known block, block after should be a pruned block. So
1563+
// canon(pruned), side, side...
1564+
1565+
// Generate fork chain, make it longer than canon
1566+
parentIndex := lastPrunedIndex + blocksBetweenCommonAncestorAndPruneblock
1567+
parent := blocks[parentIndex]
1568+
fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 2*triesInMemory, func(i int, b *BlockGen) {
1569+
b.SetCoinbase(common.Address{2})
1570+
})
1571+
// Prepend the parent(s)
1572+
var sidechain []*types.Block
1573+
for i := numCanonBlocksInSidechain; i > 0; i-- {
1574+
sidechain = append(sidechain, blocks[parentIndex+1-i])
1575+
}
1576+
sidechain = append(sidechain, fork...)
1577+
_, err = chain.InsertChain(sidechain)
1578+
if err != nil {
1579+
t.Errorf("Got error, %v", err)
1580+
}
1581+
head := chain.CurrentBlock()
1582+
if got := fork[len(fork)-1].Hash(); got != head.Hash() {
1583+
t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
1584+
}
1585+
}
1586+
1587+
// Tests that importing a sidechain (S), where
1588+
// - S is sidechain, containing blocks [Sn...Sm]
1589+
// - C is canon chain, containing blocks [G..Cn..Cm]
1590+
// - The common ancestor Cc is pruned
1591+
// - The first block in S: Sn, is == Cn
1592+
// That is: the sidechain for import contains some blocks already present in canon chain.
1593+
// So the blocks are
1594+
// [ Cn, Cn+1, Cc, Sn+3 ... Sm]
1595+
// ^ ^ ^ pruned
1596+
func TestPrunedImportSide(t *testing.T) {
1597+
//glogger := log.NewGlogHandler(log.StreamHandler(os.Stdout, log.TerminalFormat(false)))
1598+
//glogger.Verbosity(3)
1599+
//log.Root().SetHandler(log.Handler(glogger))
1600+
testSideImport(t, 3, 3)
1601+
testSideImport(t, 3, -3)
1602+
testSideImport(t, 10, 0)
1603+
testSideImport(t, 1, 10)
1604+
testSideImport(t, 1, -10)
1605+
}

0 commit comments

Comments
 (0)