Skip to content

Commit c8cf360

Browse files
authored
core: fix canonicality confusion (#19514)
* core: add tests for canonicality confusion * core: delete stale future canon number mappings during reorg to shorter+heavier chain
1 parent 14868a3 commit c8cf360

2 files changed

Lines changed: 130 additions & 1 deletion

File tree

‎core/blockchain.go‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1543,8 +1543,16 @@ func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
15431543
for _, tx := range types.TxDifference(deletedTxs, addedTxs) {
15441544
rawdb.DeleteTxLookupEntry(batch, tx.Hash())
15451545
}
1546+
// Delete any canonical number assignments above the new head
1547+
number := bc.CurrentBlock().NumberU64()
1548+
for i := number + 1; ; i++ {
1549+
hash := rawdb.ReadCanonicalHash(bc.db, i)
1550+
if hash == (common.Hash{}) {
1551+
break
1552+
}
1553+
rawdb.DeleteCanonicalHash(batch, i)
1554+
}
15461555
batch.Write()
1547-
15481556
// If any logs need to be fired, do it now. In theory we could avoid creating
15491557
// this goroutine if there are no events to fire, but realistcally that only
15501558
// ever happens if we're reorging empty blocks, which will only happen on idle

‎core/blockchain_test.go‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package core
1818

1919
import (
20+
"fmt"
2021
"math/big"
2122
"math/rand"
2223
"sync"
@@ -1810,3 +1811,123 @@ func TestPrunedImportSide(t *testing.T) {
18101811
testSideImport(t, 1, 10)
18111812
testSideImport(t, 1, -10)
18121813
}
1814+
1815+
// getLongAndShortChains returns two chains,
1816+
// A is longer, B is heavier
1817+
func getLongAndShortChains() (*BlockChain, []*types.Block, []*types.Block, error) {
1818+
// Generate a canonical chain to act as the main dataset
1819+
engine := ethash.NewFaker()
1820+
db := rawdb.NewMemoryDatabase()
1821+
genesis := new(Genesis).MustCommit(db)
1822+
1823+
// Generate and import the canonical chain,
1824+
// Offset the time, to keep the difficulty low
1825+
longChain, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 80, func(i int, b *BlockGen) {
1826+
b.SetCoinbase(common.Address{1})
1827+
})
1828+
diskdb := rawdb.NewMemoryDatabase()
1829+
new(Genesis).MustCommit(diskdb)
1830+
1831+
chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
1832+
if err != nil {
1833+
return nil, nil, nil, fmt.Errorf("failed to create tester chain: %v", err)
1834+
}
1835+
1836+
// Generate fork chain, make it shorter than canon, with common ancestor pretty early
1837+
parentIndex := 3
1838+
parent := longChain[parentIndex]
1839+
heavyChain, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 75, func(i int, b *BlockGen) {
1840+
b.SetCoinbase(common.Address{2})
1841+
b.OffsetTime(-9)
1842+
})
1843+
// Verify that the test is sane
1844+
var (
1845+
longerTd = new(big.Int)
1846+
shorterTd = new(big.Int)
1847+
)
1848+
for index, b := range longChain {
1849+
longerTd.Add(longerTd, b.Difficulty())
1850+
if index <= parentIndex {
1851+
shorterTd.Add(shorterTd, b.Difficulty())
1852+
}
1853+
}
1854+
for _, b := range heavyChain {
1855+
shorterTd.Add(shorterTd, b.Difficulty())
1856+
}
1857+
if shorterTd.Cmp(longerTd) <= 0 {
1858+
return nil, nil, nil, fmt.Errorf("Test is moot, heavyChain td (%v) must be larger than canon td (%v)", shorterTd, longerTd)
1859+
}
1860+
longerNum := longChain[len(longChain)-1].NumberU64()
1861+
shorterNum := heavyChain[len(heavyChain)-1].NumberU64()
1862+
if shorterNum >= longerNum {
1863+
return nil, nil, nil, fmt.Errorf("Test is moot, heavyChain num (%v) must be lower than canon num (%v)", shorterNum, longerNum)
1864+
}
1865+
return chain, longChain, heavyChain, nil
1866+
}
1867+
1868+
// TestReorgToShorterRemovesCanonMapping tests that if we
1869+
// 1. Have a chain [0 ... N .. X]
1870+
// 2. Reorg to shorter but heavier chain [0 ... N ... Y]
1871+
// 3. Then there should be no canon mapping for the block at height X
1872+
func TestReorgToShorterRemovesCanonMapping(t *testing.T) {
1873+
chain, canonblocks, sideblocks, err := getLongAndShortChains()
1874+
if err != nil {
1875+
t.Fatal(err)
1876+
}
1877+
if n, err := chain.InsertChain(canonblocks); err != nil {
1878+
t.Fatalf("block %d: failed to insert into chain: %v", n, err)
1879+
}
1880+
canonNum := chain.CurrentBlock().NumberU64()
1881+
_, err = chain.InsertChain(sideblocks)
1882+
if err != nil {
1883+
t.Errorf("Got error, %v", err)
1884+
}
1885+
head := chain.CurrentBlock()
1886+
if got := sideblocks[len(sideblocks)-1].Hash(); got != head.Hash() {
1887+
t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
1888+
}
1889+
// We have now inserted a sidechain.
1890+
if blockByNum := chain.GetBlockByNumber(canonNum); blockByNum != nil {
1891+
t.Errorf("expected block to be gone: %v", blockByNum.NumberU64())
1892+
}
1893+
if headerByNum := chain.GetHeaderByNumber(canonNum); headerByNum != nil {
1894+
t.Errorf("expected header to be gone: %v", headerByNum.Number.Uint64())
1895+
}
1896+
}
1897+
1898+
// TestReorgToShorterRemovesCanonMappingHeaderChain is the same scenario
1899+
// as TestReorgToShorterRemovesCanonMapping, but applied on headerchain
1900+
// imports -- that is, for fast sync
1901+
func TestReorgToShorterRemovesCanonMappingHeaderChain(t *testing.T) {
1902+
chain, canonblocks, sideblocks, err := getLongAndShortChains()
1903+
if err != nil {
1904+
t.Fatal(err)
1905+
}
1906+
// Convert into headers
1907+
canonHeaders := make([]*types.Header, len(canonblocks))
1908+
for i, block := range canonblocks {
1909+
canonHeaders[i] = block.Header()
1910+
}
1911+
if n, err := chain.InsertHeaderChain(canonHeaders, 0); err != nil {
1912+
t.Fatalf("header %d: failed to insert into chain: %v", n, err)
1913+
}
1914+
canonNum := chain.CurrentHeader().Number.Uint64()
1915+
sideHeaders := make([]*types.Header, len(sideblocks))
1916+
for i, block := range sideblocks {
1917+
sideHeaders[i] = block.Header()
1918+
}
1919+
if n, err := chain.InsertHeaderChain(sideHeaders, 0); err != nil {
1920+
t.Fatalf("header %d: failed to insert into chain: %v", n, err)
1921+
}
1922+
head := chain.CurrentHeader()
1923+
if got := sideblocks[len(sideblocks)-1].Hash(); got != head.Hash() {
1924+
t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
1925+
}
1926+
// We have now inserted a sidechain.
1927+
if blockByNum := chain.GetBlockByNumber(canonNum); blockByNum != nil {
1928+
t.Errorf("expected block to be gone: %v", blockByNum.NumberU64())
1929+
}
1930+
if headerByNum := chain.GetHeaderByNumber(canonNum); headerByNum != nil {
1931+
t.Errorf("expected header to be gone: %v", headerByNum.Number.Uint64())
1932+
}
1933+
}

0 commit comments

Comments
 (0)