blockchain_test.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "fmt"
  19. "math/big"
  20. "math/rand"
  21. "os"
  22. "path/filepath"
  23. "runtime"
  24. "strconv"
  25. "testing"
  26. "time"
  27. "github.com/ethereum/ethash"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/core/state"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/core/vm"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/params"
  36. "github.com/ethereum/go-ethereum/pow"
  37. "github.com/ethereum/go-ethereum/rlp"
  38. "github.com/hashicorp/golang-lru"
  39. )
  40. func init() {
  41. runtime.GOMAXPROCS(runtime.NumCPU())
  42. }
  43. func thePow() pow.PoW {
  44. pow, _ := ethash.NewForTesting()
  45. return pow
  46. }
  47. func theBlockChain(db ethdb.Database, t *testing.T) *BlockChain {
  48. var eventMux event.TypeMux
  49. WriteTestNetGenesisBlock(db)
  50. blockchain, err := NewBlockChain(db, thePow(), &eventMux)
  51. if err != nil {
  52. t.Error("failed creating blockchain:", err)
  53. t.FailNow()
  54. return nil
  55. }
  56. return blockchain
  57. }
  58. // Test fork of length N starting from block i
  59. func testFork(t *testing.T, blockchain *BlockChain, i, n int, full bool, comparator func(td1, td2 *big.Int)) {
  60. // Copy old chain up to #i into a new db
  61. db, blockchain2, err := newCanonical(i, full)
  62. if err != nil {
  63. t.Fatal("could not make new canonical in testFork", err)
  64. }
  65. // Assert the chains have the same header/block at #i
  66. var hash1, hash2 common.Hash
  67. if full {
  68. hash1 = blockchain.GetBlockByNumber(uint64(i)).Hash()
  69. hash2 = blockchain2.GetBlockByNumber(uint64(i)).Hash()
  70. } else {
  71. hash1 = blockchain.GetHeaderByNumber(uint64(i)).Hash()
  72. hash2 = blockchain2.GetHeaderByNumber(uint64(i)).Hash()
  73. }
  74. if hash1 != hash2 {
  75. t.Errorf("chain content mismatch at %d: have hash %v, want hash %v", i, hash2, hash1)
  76. }
  77. // Extend the newly created chain
  78. var (
  79. blockChainB []*types.Block
  80. headerChainB []*types.Header
  81. )
  82. if full {
  83. blockChainB = makeBlockChain(blockchain2.CurrentBlock(), n, db, forkSeed)
  84. if _, err := blockchain2.InsertChain(blockChainB); err != nil {
  85. t.Fatalf("failed to insert forking chain: %v", err)
  86. }
  87. } else {
  88. headerChainB = makeHeaderChain(blockchain2.CurrentHeader(), n, db, forkSeed)
  89. if _, err := blockchain2.InsertHeaderChain(headerChainB, 1); err != nil {
  90. t.Fatalf("failed to insert forking chain: %v", err)
  91. }
  92. }
  93. // Sanity check that the forked chain can be imported into the original
  94. var tdPre, tdPost *big.Int
  95. if full {
  96. tdPre = blockchain.GetTd(blockchain.CurrentBlock().Hash())
  97. if err := testBlockChainImport(blockChainB, blockchain); err != nil {
  98. t.Fatalf("failed to import forked block chain: %v", err)
  99. }
  100. tdPost = blockchain.GetTd(blockChainB[len(blockChainB)-1].Hash())
  101. } else {
  102. tdPre = blockchain.GetTd(blockchain.CurrentHeader().Hash())
  103. if err := testHeaderChainImport(headerChainB, blockchain); err != nil {
  104. t.Fatalf("failed to import forked header chain: %v", err)
  105. }
  106. tdPost = blockchain.GetTd(headerChainB[len(headerChainB)-1].Hash())
  107. }
  108. // Compare the total difficulties of the chains
  109. comparator(tdPre, tdPost)
  110. }
  111. func printChain(bc *BlockChain) {
  112. for i := bc.CurrentBlock().Number().Uint64(); i > 0; i-- {
  113. b := bc.GetBlockByNumber(uint64(i))
  114. fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty())
  115. }
  116. }
  117. // testBlockChainImport tries to process a chain of blocks, writing them into
  118. // the database if successful.
  119. func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error {
  120. for _, block := range chain {
  121. // Try and process the block
  122. err := blockchain.Validator().ValidateBlock(block)
  123. if err != nil {
  124. if IsKnownBlockErr(err) {
  125. continue
  126. }
  127. return err
  128. }
  129. statedb, err := state.New(blockchain.GetBlock(block.ParentHash()).Root(), blockchain.chainDb)
  130. if err != nil {
  131. return err
  132. }
  133. receipts, _, usedGas, err := blockchain.Processor().Process(block, statedb)
  134. if err != nil {
  135. reportBlock(block, err)
  136. return err
  137. }
  138. err = blockchain.Validator().ValidateState(block, blockchain.GetBlock(block.ParentHash()), statedb, receipts, usedGas)
  139. if err != nil {
  140. reportBlock(block, err)
  141. return err
  142. }
  143. blockchain.mu.Lock()
  144. WriteTd(blockchain.chainDb, block.Hash(), new(big.Int).Add(block.Difficulty(), blockchain.GetTd(block.ParentHash())))
  145. WriteBlock(blockchain.chainDb, block)
  146. statedb.Commit()
  147. blockchain.mu.Unlock()
  148. }
  149. return nil
  150. }
  151. // testHeaderChainImport tries to process a chain of header, writing them into
  152. // the database if successful.
  153. func testHeaderChainImport(chain []*types.Header, blockchain *BlockChain) error {
  154. for _, header := range chain {
  155. // Try and validate the header
  156. if err := blockchain.Validator().ValidateHeader(header, blockchain.GetHeader(header.ParentHash), false); err != nil {
  157. return err
  158. }
  159. // Manually insert the header into the database, but don't reorganize (allows subsequent testing)
  160. blockchain.mu.Lock()
  161. WriteTd(blockchain.chainDb, header.Hash(), new(big.Int).Add(header.Difficulty, blockchain.GetTd(header.ParentHash)))
  162. WriteHeader(blockchain.chainDb, header)
  163. blockchain.mu.Unlock()
  164. }
  165. return nil
  166. }
  167. func loadChain(fn string, t *testing.T) (types.Blocks, error) {
  168. fh, err := os.OpenFile(filepath.Join("..", "_data", fn), os.O_RDONLY, os.ModePerm)
  169. if err != nil {
  170. return nil, err
  171. }
  172. defer fh.Close()
  173. var chain types.Blocks
  174. if err := rlp.Decode(fh, &chain); err != nil {
  175. return nil, err
  176. }
  177. return chain, nil
  178. }
  179. func insertChain(done chan bool, blockchain *BlockChain, chain types.Blocks, t *testing.T) {
  180. _, err := blockchain.InsertChain(chain)
  181. if err != nil {
  182. fmt.Println(err)
  183. t.FailNow()
  184. }
  185. done <- true
  186. }
  187. func TestLastBlock(t *testing.T) {
  188. db, _ := ethdb.NewMemDatabase()
  189. bchain := theBlockChain(db, t)
  190. block := makeBlockChain(bchain.CurrentBlock(), 1, db, 0)[0]
  191. bchain.insert(block)
  192. if block.Hash() != GetHeadBlockHash(db) {
  193. t.Errorf("Write/Get HeadBlockHash failed")
  194. }
  195. }
  196. // Tests that given a starting canonical chain of a given size, it can be extended
  197. // with various length chains.
  198. func TestExtendCanonicalHeaders(t *testing.T) { testExtendCanonical(t, false) }
  199. func TestExtendCanonicalBlocks(t *testing.T) { testExtendCanonical(t, true) }
  200. func testExtendCanonical(t *testing.T, full bool) {
  201. length := 5
  202. // Make first chain starting from genesis
  203. _, processor, err := newCanonical(length, full)
  204. if err != nil {
  205. t.Fatalf("failed to make new canonical chain: %v", err)
  206. }
  207. // Define the difficulty comparator
  208. better := func(td1, td2 *big.Int) {
  209. if td2.Cmp(td1) <= 0 {
  210. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  211. }
  212. }
  213. // Start fork from current height
  214. testFork(t, processor, length, 1, full, better)
  215. testFork(t, processor, length, 2, full, better)
  216. testFork(t, processor, length, 5, full, better)
  217. testFork(t, processor, length, 10, full, better)
  218. }
  219. // Tests that given a starting canonical chain of a given size, creating shorter
  220. // forks do not take canonical ownership.
  221. func TestShorterForkHeaders(t *testing.T) { testShorterFork(t, false) }
  222. func TestShorterForkBlocks(t *testing.T) { testShorterFork(t, true) }
  223. func testShorterFork(t *testing.T, full bool) {
  224. length := 10
  225. // Make first chain starting from genesis
  226. _, processor, err := newCanonical(length, full)
  227. if err != nil {
  228. t.Fatalf("failed to make new canonical chain: %v", err)
  229. }
  230. // Define the difficulty comparator
  231. worse := func(td1, td2 *big.Int) {
  232. if td2.Cmp(td1) >= 0 {
  233. t.Errorf("total difficulty mismatch: have %v, expected less than %v", td2, td1)
  234. }
  235. }
  236. // Sum of numbers must be less than `length` for this to be a shorter fork
  237. testFork(t, processor, 0, 3, full, worse)
  238. testFork(t, processor, 0, 7, full, worse)
  239. testFork(t, processor, 1, 1, full, worse)
  240. testFork(t, processor, 1, 7, full, worse)
  241. testFork(t, processor, 5, 3, full, worse)
  242. testFork(t, processor, 5, 4, full, worse)
  243. }
  244. // Tests that given a starting canonical chain of a given size, creating longer
  245. // forks do take canonical ownership.
  246. func TestLongerForkHeaders(t *testing.T) { testLongerFork(t, false) }
  247. func TestLongerForkBlocks(t *testing.T) { testLongerFork(t, true) }
  248. func testLongerFork(t *testing.T, full bool) {
  249. length := 10
  250. // Make first chain starting from genesis
  251. _, processor, err := newCanonical(length, full)
  252. if err != nil {
  253. t.Fatalf("failed to make new canonical chain: %v", err)
  254. }
  255. // Define the difficulty comparator
  256. better := func(td1, td2 *big.Int) {
  257. if td2.Cmp(td1) <= 0 {
  258. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  259. }
  260. }
  261. // Sum of numbers must be greater than `length` for this to be a longer fork
  262. testFork(t, processor, 0, 11, full, better)
  263. testFork(t, processor, 0, 15, full, better)
  264. testFork(t, processor, 1, 10, full, better)
  265. testFork(t, processor, 1, 12, full, better)
  266. testFork(t, processor, 5, 6, full, better)
  267. testFork(t, processor, 5, 8, full, better)
  268. }
  269. // Tests that given a starting canonical chain of a given size, creating equal
  270. // forks do take canonical ownership.
  271. func TestEqualForkHeaders(t *testing.T) { testEqualFork(t, false) }
  272. func TestEqualForkBlocks(t *testing.T) { testEqualFork(t, true) }
  273. func testEqualFork(t *testing.T, full bool) {
  274. length := 10
  275. // Make first chain starting from genesis
  276. _, processor, err := newCanonical(length, full)
  277. if err != nil {
  278. t.Fatalf("failed to make new canonical chain: %v", err)
  279. }
  280. // Define the difficulty comparator
  281. equal := func(td1, td2 *big.Int) {
  282. if td2.Cmp(td1) != 0 {
  283. t.Errorf("total difficulty mismatch: have %v, want %v", td2, td1)
  284. }
  285. }
  286. // Sum of numbers must be equal to `length` for this to be an equal fork
  287. testFork(t, processor, 0, 10, full, equal)
  288. testFork(t, processor, 1, 9, full, equal)
  289. testFork(t, processor, 2, 8, full, equal)
  290. testFork(t, processor, 5, 5, full, equal)
  291. testFork(t, processor, 6, 4, full, equal)
  292. testFork(t, processor, 9, 1, full, equal)
  293. }
  294. // Tests that chains missing links do not get accepted by the processor.
  295. func TestBrokenHeaderChain(t *testing.T) { testBrokenChain(t, false) }
  296. func TestBrokenBlockChain(t *testing.T) { testBrokenChain(t, true) }
  297. func testBrokenChain(t *testing.T, full bool) {
  298. // Make chain starting from genesis
  299. db, blockchain, err := newCanonical(10, full)
  300. if err != nil {
  301. t.Fatalf("failed to make new canonical chain: %v", err)
  302. }
  303. // Create a forked chain, and try to insert with a missing link
  304. if full {
  305. chain := makeBlockChain(blockchain.CurrentBlock(), 5, db, forkSeed)[1:]
  306. if err := testBlockChainImport(chain, blockchain); err == nil {
  307. t.Errorf("broken block chain not reported")
  308. }
  309. } else {
  310. chain := makeHeaderChain(blockchain.CurrentHeader(), 5, db, forkSeed)[1:]
  311. if err := testHeaderChainImport(chain, blockchain); err == nil {
  312. t.Errorf("broken header chain not reported")
  313. }
  314. }
  315. }
  316. func TestChainInsertions(t *testing.T) {
  317. t.Skip("Skipped: outdated test files")
  318. db, _ := ethdb.NewMemDatabase()
  319. chain1, err := loadChain("valid1", t)
  320. if err != nil {
  321. fmt.Println(err)
  322. t.FailNow()
  323. }
  324. chain2, err := loadChain("valid2", t)
  325. if err != nil {
  326. fmt.Println(err)
  327. t.FailNow()
  328. }
  329. blockchain := theBlockChain(db, t)
  330. const max = 2
  331. done := make(chan bool, max)
  332. go insertChain(done, blockchain, chain1, t)
  333. go insertChain(done, blockchain, chain2, t)
  334. for i := 0; i < max; i++ {
  335. <-done
  336. }
  337. if chain2[len(chain2)-1].Hash() != blockchain.CurrentBlock().Hash() {
  338. t.Error("chain2 is canonical and shouldn't be")
  339. }
  340. if chain1[len(chain1)-1].Hash() != blockchain.CurrentBlock().Hash() {
  341. t.Error("chain1 isn't canonical and should be")
  342. }
  343. }
  344. func TestChainMultipleInsertions(t *testing.T) {
  345. t.Skip("Skipped: outdated test files")
  346. db, _ := ethdb.NewMemDatabase()
  347. const max = 4
  348. chains := make([]types.Blocks, max)
  349. var longest int
  350. for i := 0; i < max; i++ {
  351. var err error
  352. name := "valid" + strconv.Itoa(i+1)
  353. chains[i], err = loadChain(name, t)
  354. if len(chains[i]) >= len(chains[longest]) {
  355. longest = i
  356. }
  357. fmt.Println("loaded", name, "with a length of", len(chains[i]))
  358. if err != nil {
  359. fmt.Println(err)
  360. t.FailNow()
  361. }
  362. }
  363. blockchain := theBlockChain(db, t)
  364. done := make(chan bool, max)
  365. for i, chain := range chains {
  366. // XXX the go routine would otherwise reference the same (chain[3]) variable and fail
  367. i := i
  368. chain := chain
  369. go func() {
  370. insertChain(done, blockchain, chain, t)
  371. fmt.Println(i, "done")
  372. }()
  373. }
  374. for i := 0; i < max; i++ {
  375. <-done
  376. }
  377. if chains[longest][len(chains[longest])-1].Hash() != blockchain.CurrentBlock().Hash() {
  378. t.Error("Invalid canonical chain")
  379. }
  380. }
  381. type bproc struct{}
  382. func (bproc) ValidateBlock(*types.Block) error { return nil }
  383. func (bproc) ValidateHeader(*types.Header, *types.Header, bool) error { return nil }
  384. func (bproc) ValidateState(block, parent *types.Block, state *state.StateDB, receipts types.Receipts, usedGas *big.Int) error {
  385. return nil
  386. }
  387. func (bproc) Process(block *types.Block, statedb *state.StateDB) (types.Receipts, vm.Logs, *big.Int, error) {
  388. return nil, nil, nil, nil
  389. }
  390. func makeHeaderChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Header {
  391. blocks := makeBlockChainWithDiff(genesis, d, seed)
  392. headers := make([]*types.Header, len(blocks))
  393. for i, block := range blocks {
  394. headers[i] = block.Header()
  395. }
  396. return headers
  397. }
  398. func makeBlockChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Block {
  399. var chain []*types.Block
  400. for i, difficulty := range d {
  401. header := &types.Header{
  402. Coinbase: common.Address{seed},
  403. Number: big.NewInt(int64(i + 1)),
  404. Difficulty: big.NewInt(int64(difficulty)),
  405. UncleHash: types.EmptyUncleHash,
  406. TxHash: types.EmptyRootHash,
  407. ReceiptHash: types.EmptyRootHash,
  408. }
  409. if i == 0 {
  410. header.ParentHash = genesis.Hash()
  411. } else {
  412. header.ParentHash = chain[i-1].Hash()
  413. }
  414. block := types.NewBlockWithHeader(header)
  415. chain = append(chain, block)
  416. }
  417. return chain
  418. }
  419. func chm(genesis *types.Block, db ethdb.Database) *BlockChain {
  420. var eventMux event.TypeMux
  421. bc := &BlockChain{
  422. chainDb: db,
  423. genesisBlock: genesis,
  424. eventMux: &eventMux,
  425. pow: FakePow{},
  426. }
  427. valFn := func() HeaderValidator { return bc.Validator() }
  428. bc.hc, _ = NewHeaderChain(db, valFn, bc.getProcInterrupt)
  429. bc.bodyCache, _ = lru.New(100)
  430. bc.bodyRLPCache, _ = lru.New(100)
  431. bc.blockCache, _ = lru.New(100)
  432. bc.futureBlocks, _ = lru.New(100)
  433. bc.SetValidator(bproc{})
  434. bc.SetProcessor(bproc{})
  435. bc.ResetWithGenesisBlock(genesis)
  436. return bc
  437. }
  438. // Tests that reorganizing a long difficult chain after a short easy one
  439. // overwrites the canonical numbers and links in the database.
  440. func TestReorgLongHeaders(t *testing.T) { testReorgLong(t, false) }
  441. func TestReorgLongBlocks(t *testing.T) { testReorgLong(t, true) }
  442. func testReorgLong(t *testing.T, full bool) {
  443. testReorg(t, []int{1, 2, 4}, []int{1, 2, 3, 4}, 10, full)
  444. }
  445. // Tests that reorganizing a short difficult chain after a long easy one
  446. // overwrites the canonical numbers and links in the database.
  447. func TestReorgShortHeaders(t *testing.T) { testReorgShort(t, false) }
  448. func TestReorgShortBlocks(t *testing.T) { testReorgShort(t, true) }
  449. func testReorgShort(t *testing.T, full bool) {
  450. testReorg(t, []int{1, 2, 3, 4}, []int{1, 10}, 11, full)
  451. }
  452. func testReorg(t *testing.T, first, second []int, td int64, full bool) {
  453. // Create a pristine block chain
  454. db, _ := ethdb.NewMemDatabase()
  455. genesis, _ := WriteTestNetGenesisBlock(db)
  456. bc := chm(genesis, db)
  457. // Insert an easy and a difficult chain afterwards
  458. if full {
  459. bc.InsertChain(makeBlockChainWithDiff(genesis, first, 11))
  460. bc.InsertChain(makeBlockChainWithDiff(genesis, second, 22))
  461. } else {
  462. bc.InsertHeaderChain(makeHeaderChainWithDiff(genesis, first, 11), 1)
  463. bc.InsertHeaderChain(makeHeaderChainWithDiff(genesis, second, 22), 1)
  464. }
  465. // Check that the chain is valid number and link wise
  466. if full {
  467. prev := bc.CurrentBlock()
  468. for block := bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 1); block.NumberU64() != 0; prev, block = block, bc.GetBlockByNumber(block.NumberU64()-1) {
  469. if prev.ParentHash() != block.Hash() {
  470. t.Errorf("parent block hash mismatch: have %x, want %x", prev.ParentHash(), block.Hash())
  471. }
  472. }
  473. } else {
  474. prev := bc.CurrentHeader()
  475. for header := bc.GetHeaderByNumber(bc.CurrentHeader().Number.Uint64() - 1); header.Number.Uint64() != 0; prev, header = header, bc.GetHeaderByNumber(header.Number.Uint64()-1) {
  476. if prev.ParentHash != header.Hash() {
  477. t.Errorf("parent header hash mismatch: have %x, want %x", prev.ParentHash, header.Hash())
  478. }
  479. }
  480. }
  481. // Make sure the chain total difficulty is the correct one
  482. want := new(big.Int).Add(genesis.Difficulty(), big.NewInt(td))
  483. if full {
  484. if have := bc.GetTd(bc.CurrentBlock().Hash()); have.Cmp(want) != 0 {
  485. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  486. }
  487. } else {
  488. if have := bc.GetTd(bc.CurrentHeader().Hash()); have.Cmp(want) != 0 {
  489. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  490. }
  491. }
  492. }
  493. // Tests that the insertion functions detect banned hashes.
  494. func TestBadHeaderHashes(t *testing.T) { testBadHashes(t, false) }
  495. func TestBadBlockHashes(t *testing.T) { testBadHashes(t, true) }
  496. func testBadHashes(t *testing.T, full bool) {
  497. // Create a pristine block chain
  498. db, _ := ethdb.NewMemDatabase()
  499. genesis, _ := WriteTestNetGenesisBlock(db)
  500. bc := chm(genesis, db)
  501. // Create a chain, ban a hash and try to import
  502. var err error
  503. if full {
  504. blocks := makeBlockChainWithDiff(genesis, []int{1, 2, 4}, 10)
  505. BadHashes[blocks[2].Header().Hash()] = true
  506. _, err = bc.InsertChain(blocks)
  507. } else {
  508. headers := makeHeaderChainWithDiff(genesis, []int{1, 2, 4}, 10)
  509. BadHashes[headers[2].Hash()] = true
  510. _, err = bc.InsertHeaderChain(headers, 1)
  511. }
  512. if !IsBadHashError(err) {
  513. t.Errorf("error mismatch: want: BadHashError, have: %v", err)
  514. }
  515. }
  516. // Tests that bad hashes are detected on boot, and the chain rolled back to a
  517. // good state prior to the bad hash.
  518. func TestReorgBadHeaderHashes(t *testing.T) { testReorgBadHashes(t, false) }
  519. func TestReorgBadBlockHashes(t *testing.T) { testReorgBadHashes(t, true) }
  520. func testReorgBadHashes(t *testing.T, full bool) {
  521. // Create a pristine block chain
  522. db, _ := ethdb.NewMemDatabase()
  523. genesis, _ := WriteTestNetGenesisBlock(db)
  524. bc := chm(genesis, db)
  525. // Create a chain, import and ban afterwards
  526. headers := makeHeaderChainWithDiff(genesis, []int{1, 2, 3, 4}, 10)
  527. blocks := makeBlockChainWithDiff(genesis, []int{1, 2, 3, 4}, 10)
  528. if full {
  529. if _, err := bc.InsertChain(blocks); err != nil {
  530. t.Fatalf("failed to import blocks: %v", err)
  531. }
  532. if bc.CurrentBlock().Hash() != blocks[3].Hash() {
  533. t.Errorf("last block hash mismatch: have: %x, want %x", bc.CurrentBlock().Hash(), blocks[3].Header().Hash())
  534. }
  535. BadHashes[blocks[3].Header().Hash()] = true
  536. defer func() { delete(BadHashes, blocks[3].Header().Hash()) }()
  537. } else {
  538. if _, err := bc.InsertHeaderChain(headers, 1); err != nil {
  539. t.Fatalf("failed to import headers: %v", err)
  540. }
  541. if bc.CurrentHeader().Hash() != headers[3].Hash() {
  542. t.Errorf("last header hash mismatch: have: %x, want %x", bc.CurrentHeader().Hash(), headers[3].Hash())
  543. }
  544. BadHashes[headers[3].Hash()] = true
  545. defer func() { delete(BadHashes, headers[3].Hash()) }()
  546. }
  547. // Create a new chain manager and check it rolled back the state
  548. ncm, err := NewBlockChain(db, FakePow{}, new(event.TypeMux))
  549. if err != nil {
  550. t.Fatalf("failed to create new chain manager: %v", err)
  551. }
  552. if full {
  553. if ncm.CurrentBlock().Hash() != blocks[2].Header().Hash() {
  554. t.Errorf("last block hash mismatch: have: %x, want %x", ncm.CurrentBlock().Hash(), blocks[2].Header().Hash())
  555. }
  556. if blocks[2].Header().GasLimit.Cmp(ncm.GasLimit()) != 0 {
  557. t.Errorf("last block gasLimit mismatch: have: %x, want %x", ncm.GasLimit(), blocks[2].Header().GasLimit)
  558. }
  559. } else {
  560. if ncm.CurrentHeader().Hash() != headers[2].Hash() {
  561. t.Errorf("last header hash mismatch: have: %x, want %x", ncm.CurrentHeader().Hash(), headers[2].Hash())
  562. }
  563. }
  564. }
  565. // Tests chain insertions in the face of one entity containing an invalid nonce.
  566. func TestHeadersInsertNonceError(t *testing.T) { testInsertNonceError(t, false) }
  567. func TestBlocksInsertNonceError(t *testing.T) { testInsertNonceError(t, true) }
  568. func testInsertNonceError(t *testing.T, full bool) {
  569. for i := 1; i < 25 && !t.Failed(); i++ {
  570. // Create a pristine chain and database
  571. db, blockchain, err := newCanonical(0, full)
  572. if err != nil {
  573. t.Fatalf("failed to create pristine chain: %v", err)
  574. }
  575. // Create and insert a chain with a failing nonce
  576. var (
  577. failAt int
  578. failRes int
  579. failNum uint64
  580. failHash common.Hash
  581. )
  582. if full {
  583. blocks := makeBlockChain(blockchain.CurrentBlock(), i, db, 0)
  584. failAt = rand.Int() % len(blocks)
  585. failNum = blocks[failAt].NumberU64()
  586. failHash = blocks[failAt].Hash()
  587. blockchain.pow = failPow{failNum}
  588. failRes, err = blockchain.InsertChain(blocks)
  589. } else {
  590. headers := makeHeaderChain(blockchain.CurrentHeader(), i, db, 0)
  591. failAt = rand.Int() % len(headers)
  592. failNum = headers[failAt].Number.Uint64()
  593. failHash = headers[failAt].Hash()
  594. blockchain.pow = failPow{failNum}
  595. blockchain.validator = NewBlockValidator(blockchain, failPow{failNum})
  596. failRes, err = blockchain.InsertHeaderChain(headers, 1)
  597. }
  598. // Check that the returned error indicates the nonce failure.
  599. if failRes != failAt {
  600. t.Errorf("test %d: failure index mismatch: have %d, want %d", i, failRes, failAt)
  601. }
  602. if !IsBlockNonceErr(err) {
  603. t.Fatalf("test %d: error mismatch: have %v, want nonce error %T", i, err, err)
  604. }
  605. nerr := err.(*BlockNonceErr)
  606. if nerr.Number.Uint64() != failNum {
  607. t.Errorf("test %d: number mismatch: have %v, want %v", i, nerr.Number, failNum)
  608. }
  609. if nerr.Hash != failHash {
  610. t.Errorf("test %d: hash mismatch: have %x, want %x", i, nerr.Hash[:4], failHash[:4])
  611. }
  612. // Check that all no blocks after the failing block have been inserted.
  613. for j := 0; j < i-failAt; j++ {
  614. if full {
  615. if block := blockchain.GetBlockByNumber(failNum + uint64(j)); block != nil {
  616. t.Errorf("test %d: invalid block in chain: %v", i, block)
  617. }
  618. } else {
  619. if header := blockchain.GetHeaderByNumber(failNum + uint64(j)); header != nil {
  620. t.Errorf("test %d: invalid header in chain: %v", i, header)
  621. }
  622. }
  623. }
  624. }
  625. }
  626. // Tests that fast importing a block chain produces the same chain data as the
  627. // classical full block processing.
  628. func TestFastVsFullChains(t *testing.T) {
  629. // Configure and generate a sample block chain
  630. var (
  631. gendb, _ = ethdb.NewMemDatabase()
  632. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  633. address = crypto.PubkeyToAddress(key.PublicKey)
  634. funds = big.NewInt(1000000000)
  635. genesis = GenesisBlockForTesting(gendb, address, funds)
  636. )
  637. blocks, receipts := GenerateChain(genesis, gendb, 1024, func(i int, block *BlockGen) {
  638. block.SetCoinbase(common.Address{0x00})
  639. // If the block number is multiple of 3, send a few bonus transactions to the miner
  640. if i%3 == 2 {
  641. for j := 0; j < i%4+1; j++ {
  642. tx, err := types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key)
  643. if err != nil {
  644. panic(err)
  645. }
  646. block.AddTx(tx)
  647. }
  648. }
  649. // If the block number is a multiple of 5, add a few bonus uncles to the block
  650. if i%5 == 5 {
  651. block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
  652. }
  653. })
  654. // Import the chain as an archive node for the comparison baseline
  655. archiveDb, _ := ethdb.NewMemDatabase()
  656. WriteGenesisBlockForTesting(archiveDb, GenesisAccount{address, funds})
  657. archive, _ := NewBlockChain(archiveDb, FakePow{}, new(event.TypeMux))
  658. if n, err := archive.InsertChain(blocks); err != nil {
  659. t.Fatalf("failed to process block %d: %v", n, err)
  660. }
  661. // Fast import the chain as a non-archive node to test
  662. fastDb, _ := ethdb.NewMemDatabase()
  663. WriteGenesisBlockForTesting(fastDb, GenesisAccount{address, funds})
  664. fast, _ := NewBlockChain(fastDb, FakePow{}, new(event.TypeMux))
  665. headers := make([]*types.Header, len(blocks))
  666. for i, block := range blocks {
  667. headers[i] = block.Header()
  668. }
  669. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  670. t.Fatalf("failed to insert header %d: %v", n, err)
  671. }
  672. if n, err := fast.InsertReceiptChain(blocks, receipts); err != nil {
  673. t.Fatalf("failed to insert receipt %d: %v", n, err)
  674. }
  675. // Iterate over all chain data components, and cross reference
  676. for i := 0; i < len(blocks); i++ {
  677. num, hash := blocks[i].NumberU64(), blocks[i].Hash()
  678. if ftd, atd := fast.GetTd(hash), archive.GetTd(hash); ftd.Cmp(atd) != 0 {
  679. t.Errorf("block #%d [%x]: td mismatch: have %v, want %v", num, hash, ftd, atd)
  680. }
  681. if fheader, aheader := fast.GetHeader(hash), archive.GetHeader(hash); fheader.Hash() != aheader.Hash() {
  682. t.Errorf("block #%d [%x]: header mismatch: have %v, want %v", num, hash, fheader, aheader)
  683. }
  684. if fblock, ablock := fast.GetBlock(hash), archive.GetBlock(hash); fblock.Hash() != ablock.Hash() {
  685. t.Errorf("block #%d [%x]: block mismatch: have %v, want %v", num, hash, fblock, ablock)
  686. } else if types.DeriveSha(fblock.Transactions()) != types.DeriveSha(ablock.Transactions()) {
  687. t.Errorf("block #%d [%x]: transactions mismatch: have %v, want %v", num, hash, fblock.Transactions(), ablock.Transactions())
  688. } else if types.CalcUncleHash(fblock.Uncles()) != types.CalcUncleHash(ablock.Uncles()) {
  689. t.Errorf("block #%d [%x]: uncles mismatch: have %v, want %v", num, hash, fblock.Uncles(), ablock.Uncles())
  690. }
  691. if freceipts, areceipts := GetBlockReceipts(fastDb, hash), GetBlockReceipts(archiveDb, hash); types.DeriveSha(freceipts) != types.DeriveSha(areceipts) {
  692. t.Errorf("block #%d [%x]: receipts mismatch: have %v, want %v", num, hash, freceipts, areceipts)
  693. }
  694. }
  695. // Check that the canonical chains are the same between the databases
  696. for i := 0; i < len(blocks)+1; i++ {
  697. if fhash, ahash := GetCanonicalHash(fastDb, uint64(i)), GetCanonicalHash(archiveDb, uint64(i)); fhash != ahash {
  698. t.Errorf("block #%d: canonical hash mismatch: have %v, want %v", i, fhash, ahash)
  699. }
  700. }
  701. }
  702. // Tests that various import methods move the chain head pointers to the correct
  703. // positions.
  704. func TestLightVsFastVsFullChainHeads(t *testing.T) {
  705. // Configure and generate a sample block chain
  706. var (
  707. gendb, _ = ethdb.NewMemDatabase()
  708. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  709. address = crypto.PubkeyToAddress(key.PublicKey)
  710. funds = big.NewInt(1000000000)
  711. genesis = GenesisBlockForTesting(gendb, address, funds)
  712. )
  713. height := uint64(1024)
  714. blocks, receipts := GenerateChain(genesis, gendb, int(height), nil)
  715. // Configure a subchain to roll back
  716. remove := []common.Hash{}
  717. for _, block := range blocks[height/2:] {
  718. remove = append(remove, block.Hash())
  719. }
  720. // Create a small assertion method to check the three heads
  721. assert := func(t *testing.T, kind string, chain *BlockChain, header uint64, fast uint64, block uint64) {
  722. if num := chain.CurrentBlock().NumberU64(); num != block {
  723. t.Errorf("%s head block mismatch: have #%v, want #%v", kind, num, block)
  724. }
  725. if num := chain.CurrentFastBlock().NumberU64(); num != fast {
  726. t.Errorf("%s head fast-block mismatch: have #%v, want #%v", kind, num, fast)
  727. }
  728. if num := chain.CurrentHeader().Number.Uint64(); num != header {
  729. t.Errorf("%s head header mismatch: have #%v, want #%v", kind, num, header)
  730. }
  731. }
  732. // Import the chain as an archive node and ensure all pointers are updated
  733. archiveDb, _ := ethdb.NewMemDatabase()
  734. WriteGenesisBlockForTesting(archiveDb, GenesisAccount{address, funds})
  735. archive, _ := NewBlockChain(archiveDb, FakePow{}, new(event.TypeMux))
  736. if n, err := archive.InsertChain(blocks); err != nil {
  737. t.Fatalf("failed to process block %d: %v", n, err)
  738. }
  739. assert(t, "archive", archive, height, height, height)
  740. archive.Rollback(remove)
  741. assert(t, "archive", archive, height/2, height/2, height/2)
  742. // Import the chain as a non-archive node and ensure all pointers are updated
  743. fastDb, _ := ethdb.NewMemDatabase()
  744. WriteGenesisBlockForTesting(fastDb, GenesisAccount{address, funds})
  745. fast, _ := NewBlockChain(fastDb, FakePow{}, new(event.TypeMux))
  746. headers := make([]*types.Header, len(blocks))
  747. for i, block := range blocks {
  748. headers[i] = block.Header()
  749. }
  750. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  751. t.Fatalf("failed to insert header %d: %v", n, err)
  752. }
  753. if n, err := fast.InsertReceiptChain(blocks, receipts); err != nil {
  754. t.Fatalf("failed to insert receipt %d: %v", n, err)
  755. }
  756. assert(t, "fast", fast, height, height, 0)
  757. fast.Rollback(remove)
  758. assert(t, "fast", fast, height/2, height/2, 0)
  759. // Import the chain as a light node and ensure all pointers are updated
  760. lightDb, _ := ethdb.NewMemDatabase()
  761. WriteGenesisBlockForTesting(lightDb, GenesisAccount{address, funds})
  762. light, _ := NewBlockChain(lightDb, FakePow{}, new(event.TypeMux))
  763. if n, err := light.InsertHeaderChain(headers, 1); err != nil {
  764. t.Fatalf("failed to insert header %d: %v", n, err)
  765. }
  766. assert(t, "light", light, height, 0, 0)
  767. light.Rollback(remove)
  768. assert(t, "light", light, height/2, 0, 0)
  769. }
  770. // Tests that chain reorganizations handle transaction removals and reinsertions.
  771. func TestChainTxReorgs(t *testing.T) {
  772. params.MinGasLimit = big.NewInt(125000) // Minimum the gas limit may ever be.
  773. params.GenesisGasLimit = big.NewInt(3141592) // Gas limit of the Genesis block.
  774. var (
  775. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  776. key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  777. key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  778. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  779. addr2 = crypto.PubkeyToAddress(key2.PublicKey)
  780. addr3 = crypto.PubkeyToAddress(key3.PublicKey)
  781. db, _ = ethdb.NewMemDatabase()
  782. )
  783. genesis := WriteGenesisBlockForTesting(db,
  784. GenesisAccount{addr1, big.NewInt(1000000)},
  785. GenesisAccount{addr2, big.NewInt(1000000)},
  786. GenesisAccount{addr3, big.NewInt(1000000)},
  787. )
  788. // Create two transactions shared between the chains:
  789. // - postponed: transaction included at a later block in the forked chain
  790. // - swapped: transaction included at the same block number in the forked chain
  791. postponed, _ := types.NewTransaction(0, addr1, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
  792. swapped, _ := types.NewTransaction(1, addr1, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
  793. // Create two transactions that will be dropped by the forked chain:
  794. // - pastDrop: transaction dropped retroactively from a past block
  795. // - freshDrop: transaction dropped exactly at the block where the reorg is detected
  796. var pastDrop, freshDrop *types.Transaction
  797. // Create three transactions that will be added in the forked chain:
  798. // - pastAdd: transaction added before the reorganization is detected
  799. // - freshAdd: transaction added at the exact block the reorg is detected
  800. // - futureAdd: transaction added after the reorg has already finished
  801. var pastAdd, freshAdd, futureAdd *types.Transaction
  802. chain, _ := GenerateChain(genesis, db, 3, func(i int, gen *BlockGen) {
  803. switch i {
  804. case 0:
  805. pastDrop, _ = types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
  806. gen.AddTx(pastDrop) // This transaction will be dropped in the fork from below the split point
  807. gen.AddTx(postponed) // This transaction will be postponed till block #3 in the fork
  808. case 2:
  809. freshDrop, _ = types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
  810. gen.AddTx(freshDrop) // This transaction will be dropped in the fork from exactly at the split point
  811. gen.AddTx(swapped) // This transaction will be swapped out at the exact height
  812. gen.OffsetTime(9) // Lower the block difficulty to simulate a weaker chain
  813. }
  814. })
  815. // Import the chain. This runs all block validation rules.
  816. evmux := &event.TypeMux{}
  817. blockchain, _ := NewBlockChain(db, FakePow{}, evmux)
  818. if i, err := blockchain.InsertChain(chain); err != nil {
  819. t.Fatalf("failed to insert original chain[%d]: %v", i, err)
  820. }
  821. // overwrite the old chain
  822. chain, _ = GenerateChain(genesis, db, 5, func(i int, gen *BlockGen) {
  823. switch i {
  824. case 0:
  825. pastAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
  826. gen.AddTx(pastAdd) // This transaction needs to be injected during reorg
  827. case 2:
  828. gen.AddTx(postponed) // This transaction was postponed from block #1 in the original chain
  829. gen.AddTx(swapped) // This transaction was swapped from the exact current spot in the original chain
  830. freshAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
  831. gen.AddTx(freshAdd) // This transaction will be added exactly at reorg time
  832. case 3:
  833. futureAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
  834. gen.AddTx(futureAdd) // This transaction will be added after a full reorg
  835. }
  836. })
  837. if _, err := blockchain.InsertChain(chain); err != nil {
  838. t.Fatalf("failed to insert forked chain: %v", err)
  839. }
  840. // removed tx
  841. for i, tx := range (types.Transactions{pastDrop, freshDrop}) {
  842. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn != nil {
  843. t.Errorf("drop %d: tx %v found while shouldn't have been", i, txn)
  844. }
  845. if GetReceipt(db, tx.Hash()) != nil {
  846. t.Errorf("drop %d: receipt found while shouldn't have been", i)
  847. }
  848. }
  849. // added tx
  850. for i, tx := range (types.Transactions{pastAdd, freshAdd, futureAdd}) {
  851. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn == nil {
  852. t.Errorf("add %d: expected tx to be found", i)
  853. }
  854. if GetReceipt(db, tx.Hash()) == nil {
  855. t.Errorf("add %d: expected receipt to be found", i)
  856. }
  857. }
  858. // shared tx
  859. for i, tx := range (types.Transactions{postponed, swapped}) {
  860. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn == nil {
  861. t.Errorf("share %d: expected tx to be found", i)
  862. }
  863. if GetReceipt(db, tx.Hash()) == nil {
  864. t.Errorf("share %d: expected receipt to be found", i)
  865. }
  866. }
  867. }
  868. func TestLogReorgs(t *testing.T) {
  869. params.MinGasLimit = big.NewInt(125000) // Minimum the gas limit may ever be.
  870. params.GenesisGasLimit = big.NewInt(3141592) // Gas limit of the Genesis block.
  871. var (
  872. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  873. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  874. db, _ = ethdb.NewMemDatabase()
  875. // this code generates a log
  876. code = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
  877. )
  878. genesis := WriteGenesisBlockForTesting(db,
  879. GenesisAccount{addr1, big.NewInt(10000000000000)},
  880. )
  881. evmux := &event.TypeMux{}
  882. blockchain, _ := NewBlockChain(db, FakePow{}, evmux)
  883. subs := evmux.Subscribe(RemovedLogsEvent{})
  884. chain, _ := GenerateChain(genesis, db, 2, func(i int, gen *BlockGen) {
  885. if i == 1 {
  886. tx, err := types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), big.NewInt(1000000), new(big.Int), code).SignECDSA(key1)
  887. if err != nil {
  888. t.Fatalf("failed to create tx: %v", err)
  889. }
  890. gen.AddTx(tx)
  891. }
  892. })
  893. if _, err := blockchain.InsertChain(chain); err != nil {
  894. t.Fatalf("failed to insert chain: %v", err)
  895. }
  896. chain, _ = GenerateChain(genesis, db, 3, func(i int, gen *BlockGen) {})
  897. if _, err := blockchain.InsertChain(chain); err != nil {
  898. t.Fatalf("failed to insert forked chain: %v", err)
  899. }
  900. ev := <-subs.Chan()
  901. if len(ev.Data.(RemovedLogsEvent).Logs) == 0 {
  902. t.Error("expected logs")
  903. }
  904. }
  905. func TestReorgSideEvent(t *testing.T) {
  906. var (
  907. db, _ = ethdb.NewMemDatabase()
  908. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  909. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  910. genesis = WriteGenesisBlockForTesting(db, GenesisAccount{addr1, big.NewInt(10000000000000)})
  911. )
  912. evmux := &event.TypeMux{}
  913. blockchain, _ := NewBlockChain(db, FakePow{}, evmux)
  914. chain, _ := GenerateChain(genesis, db, 3, func(i int, gen *BlockGen) {
  915. if i == 2 {
  916. gen.OffsetTime(9)
  917. }
  918. })
  919. if _, err := blockchain.InsertChain(chain); err != nil {
  920. t.Fatalf("failed to insert chain: %v", err)
  921. }
  922. replacementBlocks, _ := GenerateChain(genesis, db, 4, func(i int, gen *BlockGen) {
  923. tx, err := types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), big.NewInt(1000000), new(big.Int), nil).SignECDSA(key1)
  924. if err != nil {
  925. t.Fatalf("failed to create tx: %v", err)
  926. }
  927. gen.AddTx(tx)
  928. })
  929. subs := evmux.Subscribe(ChainSideEvent{})
  930. if _, err := blockchain.InsertChain(replacementBlocks); err != nil {
  931. t.Fatalf("failed to insert chain: %v", err)
  932. }
  933. // first two block of the secondary chain are for a brief moment considered
  934. // side chains because up to that point the first one is considered the
  935. // heavier chain.
  936. expectedSideHashes := map[common.Hash]bool{
  937. replacementBlocks[0].Hash(): true,
  938. replacementBlocks[1].Hash(): true,
  939. chain[0].Hash(): true,
  940. chain[1].Hash(): true,
  941. chain[2].Hash(): true,
  942. }
  943. i := 0
  944. const timeoutDura = 10 * time.Second
  945. timeout := time.NewTimer(timeoutDura)
  946. done:
  947. for {
  948. select {
  949. case ev := <-subs.Chan():
  950. block := ev.Data.(ChainSideEvent).Block
  951. if _, ok := expectedSideHashes[block.Hash()]; !ok {
  952. t.Errorf("%d: didn't expect %x to be in side chain", i, block.Hash())
  953. }
  954. i++
  955. if i == len(expectedSideHashes) {
  956. timeout.Stop()
  957. break done
  958. }
  959. timeout.Reset(timeoutDura)
  960. case <-timeout.C:
  961. t.Fatal("Timeout. Possibly not all blocks were triggered for sideevent")
  962. }
  963. }
  964. // make sure no more events are fired
  965. select {
  966. case e := <-subs.Chan():
  967. t.Errorf("unexpected event fired: %v", e)
  968. case <-time.After(250 * time.Millisecond):
  969. }
  970. }