blockchain_test.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  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, testChainConfig(), 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.GetTdByHash(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.GetTdByHash(blockChainB[len(blockChainB)-1].Hash())
  101. } else {
  102. tdPre = blockchain.GetTdByHash(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.GetTdByHash(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.GetBlockByHash(block.ParentHash()).Root(), blockchain.chainDb)
  130. if err != nil {
  131. return err
  132. }
  133. receipts, _, usedGas, err := blockchain.Processor().Process(block, statedb, vm.Config{})
  134. if err != nil {
  135. blockchain.reportBlock(block, receipts, err)
  136. return err
  137. }
  138. err = blockchain.Validator().ValidateState(block, blockchain.GetBlockByHash(block.ParentHash()), statedb, receipts, usedGas)
  139. if err != nil {
  140. blockchain.reportBlock(block, receipts, err)
  141. return err
  142. }
  143. blockchain.mu.Lock()
  144. WriteTd(blockchain.chainDb, block.Hash(), block.NumberU64(), new(big.Int).Add(block.Difficulty(), blockchain.GetTdByHash(block.ParentHash())))
  145. WriteBlock(blockchain.chainDb, block)
  146. statedb.Commit(false)
  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.GetHeaderByHash(header.ParentHash), false); err != nil {
  157. return err
  158. }
  159. // Manually insert the header into the database, but don't reorganise (allows subsequent testing)
  160. blockchain.mu.Lock()
  161. WriteTd(blockchain.chainDb, header.Hash(), header.Number.Uint64(), new(big.Int).Add(header.Difficulty, blockchain.GetTdByHash(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, cfg vm.Config) (types.Receipts, []*types.Log, *big.Int, error) {
  388. return nil, nil, new(big.Int), 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. config: testChainConfig(),
  427. }
  428. valFn := func() HeaderValidator { return bc.Validator() }
  429. bc.hc, _ = NewHeaderChain(db, testChainConfig(), valFn, bc.getProcInterrupt)
  430. bc.bodyCache, _ = lru.New(100)
  431. bc.bodyRLPCache, _ = lru.New(100)
  432. bc.blockCache, _ = lru.New(100)
  433. bc.futureBlocks, _ = lru.New(100)
  434. bc.SetValidator(bproc{})
  435. bc.SetProcessor(bproc{})
  436. bc.ResetWithGenesisBlock(genesis)
  437. return bc
  438. }
  439. // Tests that reorganising a long difficult chain after a short easy one
  440. // overwrites the canonical numbers and links in the database.
  441. func TestReorgLongHeaders(t *testing.T) { testReorgLong(t, false) }
  442. func TestReorgLongBlocks(t *testing.T) { testReorgLong(t, true) }
  443. func testReorgLong(t *testing.T, full bool) {
  444. testReorg(t, []int{1, 2, 4}, []int{1, 2, 3, 4}, 10, full)
  445. }
  446. // Tests that reorganising a short difficult chain after a long easy one
  447. // overwrites the canonical numbers and links in the database.
  448. func TestReorgShortHeaders(t *testing.T) { testReorgShort(t, false) }
  449. func TestReorgShortBlocks(t *testing.T) { testReorgShort(t, true) }
  450. func testReorgShort(t *testing.T, full bool) {
  451. testReorg(t, []int{1, 2, 3, 4}, []int{1, 10}, 11, full)
  452. }
  453. func testReorg(t *testing.T, first, second []int, td int64, full bool) {
  454. // Create a pristine block chain
  455. db, _ := ethdb.NewMemDatabase()
  456. genesis, _ := WriteTestNetGenesisBlock(db)
  457. bc := chm(genesis, db)
  458. // Insert an easy and a difficult chain afterwards
  459. if full {
  460. bc.InsertChain(makeBlockChainWithDiff(genesis, first, 11))
  461. bc.InsertChain(makeBlockChainWithDiff(genesis, second, 22))
  462. } else {
  463. bc.InsertHeaderChain(makeHeaderChainWithDiff(genesis, first, 11), 1)
  464. bc.InsertHeaderChain(makeHeaderChainWithDiff(genesis, second, 22), 1)
  465. }
  466. // Check that the chain is valid number and link wise
  467. if full {
  468. prev := bc.CurrentBlock()
  469. for block := bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 1); block.NumberU64() != 0; prev, block = block, bc.GetBlockByNumber(block.NumberU64()-1) {
  470. if prev.ParentHash() != block.Hash() {
  471. t.Errorf("parent block hash mismatch: have %x, want %x", prev.ParentHash(), block.Hash())
  472. }
  473. }
  474. } else {
  475. prev := bc.CurrentHeader()
  476. for header := bc.GetHeaderByNumber(bc.CurrentHeader().Number.Uint64() - 1); header.Number.Uint64() != 0; prev, header = header, bc.GetHeaderByNumber(header.Number.Uint64()-1) {
  477. if prev.ParentHash != header.Hash() {
  478. t.Errorf("parent header hash mismatch: have %x, want %x", prev.ParentHash, header.Hash())
  479. }
  480. }
  481. }
  482. // Make sure the chain total difficulty is the correct one
  483. want := new(big.Int).Add(genesis.Difficulty(), big.NewInt(td))
  484. if full {
  485. if have := bc.GetTdByHash(bc.CurrentBlock().Hash()); have.Cmp(want) != 0 {
  486. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  487. }
  488. } else {
  489. if have := bc.GetTdByHash(bc.CurrentHeader().Hash()); have.Cmp(want) != 0 {
  490. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  491. }
  492. }
  493. }
  494. // Tests that the insertion functions detect banned hashes.
  495. func TestBadHeaderHashes(t *testing.T) { testBadHashes(t, false) }
  496. func TestBadBlockHashes(t *testing.T) { testBadHashes(t, true) }
  497. func testBadHashes(t *testing.T, full bool) {
  498. // Create a pristine block chain
  499. db, _ := ethdb.NewMemDatabase()
  500. genesis, _ := WriteTestNetGenesisBlock(db)
  501. bc := chm(genesis, db)
  502. // Create a chain, ban a hash and try to import
  503. var err error
  504. if full {
  505. blocks := makeBlockChainWithDiff(genesis, []int{1, 2, 4}, 10)
  506. BadHashes[blocks[2].Header().Hash()] = true
  507. _, err = bc.InsertChain(blocks)
  508. } else {
  509. headers := makeHeaderChainWithDiff(genesis, []int{1, 2, 4}, 10)
  510. BadHashes[headers[2].Hash()] = true
  511. _, err = bc.InsertHeaderChain(headers, 1)
  512. }
  513. if !IsBadHashError(err) {
  514. t.Errorf("error mismatch: want: BadHashError, have: %v", err)
  515. }
  516. }
  517. // Tests that bad hashes are detected on boot, and the chain rolled back to a
  518. // good state prior to the bad hash.
  519. func TestReorgBadHeaderHashes(t *testing.T) { testReorgBadHashes(t, false) }
  520. func TestReorgBadBlockHashes(t *testing.T) { testReorgBadHashes(t, true) }
  521. func testReorgBadHashes(t *testing.T, full bool) {
  522. // Create a pristine block chain
  523. db, _ := ethdb.NewMemDatabase()
  524. genesis, _ := WriteTestNetGenesisBlock(db)
  525. bc := chm(genesis, db)
  526. // Create a chain, import and ban afterwards
  527. headers := makeHeaderChainWithDiff(genesis, []int{1, 2, 3, 4}, 10)
  528. blocks := makeBlockChainWithDiff(genesis, []int{1, 2, 3, 4}, 10)
  529. if full {
  530. if _, err := bc.InsertChain(blocks); err != nil {
  531. t.Fatalf("failed to import blocks: %v", err)
  532. }
  533. if bc.CurrentBlock().Hash() != blocks[3].Hash() {
  534. t.Errorf("last block hash mismatch: have: %x, want %x", bc.CurrentBlock().Hash(), blocks[3].Header().Hash())
  535. }
  536. BadHashes[blocks[3].Header().Hash()] = true
  537. defer func() { delete(BadHashes, blocks[3].Header().Hash()) }()
  538. } else {
  539. if _, err := bc.InsertHeaderChain(headers, 1); err != nil {
  540. t.Fatalf("failed to import headers: %v", err)
  541. }
  542. if bc.CurrentHeader().Hash() != headers[3].Hash() {
  543. t.Errorf("last header hash mismatch: have: %x, want %x", bc.CurrentHeader().Hash(), headers[3].Hash())
  544. }
  545. BadHashes[headers[3].Hash()] = true
  546. defer func() { delete(BadHashes, headers[3].Hash()) }()
  547. }
  548. // Create a new chain manager and check it rolled back the state
  549. ncm, err := NewBlockChain(db, testChainConfig(), FakePow{}, new(event.TypeMux))
  550. if err != nil {
  551. t.Fatalf("failed to create new chain manager: %v", err)
  552. }
  553. if full {
  554. if ncm.CurrentBlock().Hash() != blocks[2].Header().Hash() {
  555. t.Errorf("last block hash mismatch: have: %x, want %x", ncm.CurrentBlock().Hash(), blocks[2].Header().Hash())
  556. }
  557. if blocks[2].Header().GasLimit.Cmp(ncm.GasLimit()) != 0 {
  558. t.Errorf("last block gasLimit mismatch: have: %x, want %x", ncm.GasLimit(), blocks[2].Header().GasLimit)
  559. }
  560. } else {
  561. if ncm.CurrentHeader().Hash() != headers[2].Hash() {
  562. t.Errorf("last header hash mismatch: have: %x, want %x", ncm.CurrentHeader().Hash(), headers[2].Hash())
  563. }
  564. }
  565. }
  566. // Tests chain insertions in the face of one entity containing an invalid nonce.
  567. func TestHeadersInsertNonceError(t *testing.T) { testInsertNonceError(t, false) }
  568. func TestBlocksInsertNonceError(t *testing.T) { testInsertNonceError(t, true) }
  569. func testInsertNonceError(t *testing.T, full bool) {
  570. for i := 1; i < 25 && !t.Failed(); i++ {
  571. // Create a pristine chain and database
  572. db, blockchain, err := newCanonical(0, full)
  573. if err != nil {
  574. t.Fatalf("failed to create pristine chain: %v", err)
  575. }
  576. // Create and insert a chain with a failing nonce
  577. var (
  578. failAt int
  579. failRes int
  580. failNum uint64
  581. failHash common.Hash
  582. )
  583. if full {
  584. blocks := makeBlockChain(blockchain.CurrentBlock(), i, db, 0)
  585. failAt = rand.Int() % len(blocks)
  586. failNum = blocks[failAt].NumberU64()
  587. failHash = blocks[failAt].Hash()
  588. blockchain.pow = failPow{failNum}
  589. failRes, err = blockchain.InsertChain(blocks)
  590. } else {
  591. headers := makeHeaderChain(blockchain.CurrentHeader(), i, db, 0)
  592. failAt = rand.Int() % len(headers)
  593. failNum = headers[failAt].Number.Uint64()
  594. failHash = headers[failAt].Hash()
  595. blockchain.pow = failPow{failNum}
  596. blockchain.validator = NewBlockValidator(testChainConfig(), blockchain, failPow{failNum})
  597. failRes, err = blockchain.InsertHeaderChain(headers, 1)
  598. }
  599. // Check that the returned error indicates the nonce failure.
  600. if failRes != failAt {
  601. t.Errorf("test %d: failure index mismatch: have %d, want %d", i, failRes, failAt)
  602. }
  603. if !IsBlockNonceErr(err) {
  604. t.Fatalf("test %d: error mismatch: have %v, want nonce error %T", i, err, err)
  605. }
  606. nerr := err.(*BlockNonceErr)
  607. if nerr.Number.Uint64() != failNum {
  608. t.Errorf("test %d: number mismatch: have %v, want %v", i, nerr.Number, failNum)
  609. }
  610. if nerr.Hash != failHash {
  611. t.Errorf("test %d: hash mismatch: have %x, want %x", i, nerr.Hash[:4], failHash[:4])
  612. }
  613. // Check that all no blocks after the failing block have been inserted.
  614. for j := 0; j < i-failAt; j++ {
  615. if full {
  616. if block := blockchain.GetBlockByNumber(failNum + uint64(j)); block != nil {
  617. t.Errorf("test %d: invalid block in chain: %v", i, block)
  618. }
  619. } else {
  620. if header := blockchain.GetHeaderByNumber(failNum + uint64(j)); header != nil {
  621. t.Errorf("test %d: invalid header in chain: %v", i, header)
  622. }
  623. }
  624. }
  625. }
  626. }
  627. // Tests that fast importing a block chain produces the same chain data as the
  628. // classical full block processing.
  629. func TestFastVsFullChains(t *testing.T) {
  630. // Configure and generate a sample block chain
  631. var (
  632. gendb, _ = ethdb.NewMemDatabase()
  633. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  634. address = crypto.PubkeyToAddress(key.PublicKey)
  635. funds = big.NewInt(1000000000)
  636. genesis = GenesisBlockForTesting(gendb, address, funds)
  637. signer = types.NewEIP155Signer(big.NewInt(1))
  638. )
  639. blocks, receipts := GenerateChain(params.TestChainConfig, genesis, gendb, 1024, func(i int, block *BlockGen) {
  640. block.SetCoinbase(common.Address{0x00})
  641. // If the block number is multiple of 3, send a few bonus transactions to the miner
  642. if i%3 == 2 {
  643. for j := 0; j < i%4+1; j++ {
  644. tx, err := types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(signer, key)
  645. if err != nil {
  646. panic(err)
  647. }
  648. block.AddTx(tx)
  649. }
  650. }
  651. // If the block number is a multiple of 5, add a few bonus uncles to the block
  652. if i%5 == 5 {
  653. block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
  654. }
  655. })
  656. // Import the chain as an archive node for the comparison baseline
  657. archiveDb, _ := ethdb.NewMemDatabase()
  658. WriteGenesisBlockForTesting(archiveDb, GenesisAccount{address, funds})
  659. archive, _ := NewBlockChain(archiveDb, testChainConfig(), FakePow{}, new(event.TypeMux))
  660. if n, err := archive.InsertChain(blocks); err != nil {
  661. t.Fatalf("failed to process block %d: %v", n, err)
  662. }
  663. // Fast import the chain as a non-archive node to test
  664. fastDb, _ := ethdb.NewMemDatabase()
  665. WriteGenesisBlockForTesting(fastDb, GenesisAccount{address, funds})
  666. fast, _ := NewBlockChain(fastDb, testChainConfig(), FakePow{}, new(event.TypeMux))
  667. headers := make([]*types.Header, len(blocks))
  668. for i, block := range blocks {
  669. headers[i] = block.Header()
  670. }
  671. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  672. t.Fatalf("failed to insert header %d: %v", n, err)
  673. }
  674. if n, err := fast.InsertReceiptChain(blocks, receipts); err != nil {
  675. t.Fatalf("failed to insert receipt %d: %v", n, err)
  676. }
  677. // Iterate over all chain data components, and cross reference
  678. for i := 0; i < len(blocks); i++ {
  679. num, hash := blocks[i].NumberU64(), blocks[i].Hash()
  680. if ftd, atd := fast.GetTdByHash(hash), archive.GetTdByHash(hash); ftd.Cmp(atd) != 0 {
  681. t.Errorf("block #%d [%x]: td mismatch: have %v, want %v", num, hash, ftd, atd)
  682. }
  683. if fheader, aheader := fast.GetHeaderByHash(hash), archive.GetHeaderByHash(hash); fheader.Hash() != aheader.Hash() {
  684. t.Errorf("block #%d [%x]: header mismatch: have %v, want %v", num, hash, fheader, aheader)
  685. }
  686. if fblock, ablock := fast.GetBlockByHash(hash), archive.GetBlockByHash(hash); fblock.Hash() != ablock.Hash() {
  687. t.Errorf("block #%d [%x]: block mismatch: have %v, want %v", num, hash, fblock, ablock)
  688. } else if types.DeriveSha(fblock.Transactions()) != types.DeriveSha(ablock.Transactions()) {
  689. t.Errorf("block #%d [%x]: transactions mismatch: have %v, want %v", num, hash, fblock.Transactions(), ablock.Transactions())
  690. } else if types.CalcUncleHash(fblock.Uncles()) != types.CalcUncleHash(ablock.Uncles()) {
  691. t.Errorf("block #%d [%x]: uncles mismatch: have %v, want %v", num, hash, fblock.Uncles(), ablock.Uncles())
  692. }
  693. if freceipts, areceipts := GetBlockReceipts(fastDb, hash, GetBlockNumber(fastDb, hash)), GetBlockReceipts(archiveDb, hash, GetBlockNumber(archiveDb, hash)); types.DeriveSha(freceipts) != types.DeriveSha(areceipts) {
  694. t.Errorf("block #%d [%x]: receipts mismatch: have %v, want %v", num, hash, freceipts, areceipts)
  695. }
  696. }
  697. // Check that the canonical chains are the same between the databases
  698. for i := 0; i < len(blocks)+1; i++ {
  699. if fhash, ahash := GetCanonicalHash(fastDb, uint64(i)), GetCanonicalHash(archiveDb, uint64(i)); fhash != ahash {
  700. t.Errorf("block #%d: canonical hash mismatch: have %v, want %v", i, fhash, ahash)
  701. }
  702. }
  703. }
  704. // Tests that various import methods move the chain head pointers to the correct
  705. // positions.
  706. func TestLightVsFastVsFullChainHeads(t *testing.T) {
  707. // Configure and generate a sample block chain
  708. var (
  709. gendb, _ = ethdb.NewMemDatabase()
  710. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  711. address = crypto.PubkeyToAddress(key.PublicKey)
  712. funds = big.NewInt(1000000000)
  713. genesis = GenesisBlockForTesting(gendb, address, funds)
  714. )
  715. height := uint64(1024)
  716. blocks, receipts := GenerateChain(params.TestChainConfig, genesis, gendb, int(height), nil)
  717. // Configure a subchain to roll back
  718. remove := []common.Hash{}
  719. for _, block := range blocks[height/2:] {
  720. remove = append(remove, block.Hash())
  721. }
  722. // Create a small assertion method to check the three heads
  723. assert := func(t *testing.T, kind string, chain *BlockChain, header uint64, fast uint64, block uint64) {
  724. if num := chain.CurrentBlock().NumberU64(); num != block {
  725. t.Errorf("%s head block mismatch: have #%v, want #%v", kind, num, block)
  726. }
  727. if num := chain.CurrentFastBlock().NumberU64(); num != fast {
  728. t.Errorf("%s head fast-block mismatch: have #%v, want #%v", kind, num, fast)
  729. }
  730. if num := chain.CurrentHeader().Number.Uint64(); num != header {
  731. t.Errorf("%s head header mismatch: have #%v, want #%v", kind, num, header)
  732. }
  733. }
  734. // Import the chain as an archive node and ensure all pointers are updated
  735. archiveDb, _ := ethdb.NewMemDatabase()
  736. WriteGenesisBlockForTesting(archiveDb, GenesisAccount{address, funds})
  737. archive, _ := NewBlockChain(archiveDb, testChainConfig(), FakePow{}, new(event.TypeMux))
  738. if n, err := archive.InsertChain(blocks); err != nil {
  739. t.Fatalf("failed to process block %d: %v", n, err)
  740. }
  741. assert(t, "archive", archive, height, height, height)
  742. archive.Rollback(remove)
  743. assert(t, "archive", archive, height/2, height/2, height/2)
  744. // Import the chain as a non-archive node and ensure all pointers are updated
  745. fastDb, _ := ethdb.NewMemDatabase()
  746. WriteGenesisBlockForTesting(fastDb, GenesisAccount{address, funds})
  747. fast, _ := NewBlockChain(fastDb, testChainConfig(), FakePow{}, new(event.TypeMux))
  748. headers := make([]*types.Header, len(blocks))
  749. for i, block := range blocks {
  750. headers[i] = block.Header()
  751. }
  752. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  753. t.Fatalf("failed to insert header %d: %v", n, err)
  754. }
  755. if n, err := fast.InsertReceiptChain(blocks, receipts); err != nil {
  756. t.Fatalf("failed to insert receipt %d: %v", n, err)
  757. }
  758. assert(t, "fast", fast, height, height, 0)
  759. fast.Rollback(remove)
  760. assert(t, "fast", fast, height/2, height/2, 0)
  761. // Import the chain as a light node and ensure all pointers are updated
  762. lightDb, _ := ethdb.NewMemDatabase()
  763. WriteGenesisBlockForTesting(lightDb, GenesisAccount{address, funds})
  764. light, _ := NewBlockChain(lightDb, testChainConfig(), FakePow{}, new(event.TypeMux))
  765. if n, err := light.InsertHeaderChain(headers, 1); err != nil {
  766. t.Fatalf("failed to insert header %d: %v", n, err)
  767. }
  768. assert(t, "light", light, height, 0, 0)
  769. light.Rollback(remove)
  770. assert(t, "light", light, height/2, 0, 0)
  771. }
  772. // Tests that chain reorganisations handle transaction removals and reinsertions.
  773. func TestChainTxReorgs(t *testing.T) {
  774. params.MinGasLimit = big.NewInt(125000) // Minimum the gas limit may ever be.
  775. params.GenesisGasLimit = big.NewInt(3141592) // Gas limit of the Genesis block.
  776. var (
  777. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  778. key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  779. key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  780. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  781. addr2 = crypto.PubkeyToAddress(key2.PublicKey)
  782. addr3 = crypto.PubkeyToAddress(key3.PublicKey)
  783. db, _ = ethdb.NewMemDatabase()
  784. signer = types.NewEIP155Signer(big.NewInt(1))
  785. )
  786. genesis := WriteGenesisBlockForTesting(db,
  787. GenesisAccount{addr1, big.NewInt(1000000)},
  788. GenesisAccount{addr2, big.NewInt(1000000)},
  789. GenesisAccount{addr3, big.NewInt(1000000)},
  790. )
  791. // Create two transactions shared between the chains:
  792. // - postponed: transaction included at a later block in the forked chain
  793. // - swapped: transaction included at the same block number in the forked chain
  794. postponed, _ := types.NewTransaction(0, addr1, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(signer, key1)
  795. swapped, _ := types.NewTransaction(1, addr1, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(signer, key1)
  796. // Create two transactions that will be dropped by the forked chain:
  797. // - pastDrop: transaction dropped retroactively from a past block
  798. // - freshDrop: transaction dropped exactly at the block where the reorg is detected
  799. var pastDrop, freshDrop *types.Transaction
  800. // Create three transactions that will be added in the forked chain:
  801. // - pastAdd: transaction added before the reorganization is detected
  802. // - freshAdd: transaction added at the exact block the reorg is detected
  803. // - futureAdd: transaction added after the reorg has already finished
  804. var pastAdd, freshAdd, futureAdd *types.Transaction
  805. chain, _ := GenerateChain(params.TestChainConfig, genesis, db, 3, func(i int, gen *BlockGen) {
  806. switch i {
  807. case 0:
  808. pastDrop, _ = types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(signer, key2)
  809. gen.AddTx(pastDrop) // This transaction will be dropped in the fork from below the split point
  810. gen.AddTx(postponed) // This transaction will be postponed till block #3 in the fork
  811. case 2:
  812. freshDrop, _ = types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(signer, key2)
  813. gen.AddTx(freshDrop) // This transaction will be dropped in the fork from exactly at the split point
  814. gen.AddTx(swapped) // This transaction will be swapped out at the exact height
  815. gen.OffsetTime(9) // Lower the block difficulty to simulate a weaker chain
  816. }
  817. })
  818. // Import the chain. This runs all block validation rules.
  819. evmux := &event.TypeMux{}
  820. blockchain, _ := NewBlockChain(db, testChainConfig(), FakePow{}, evmux)
  821. if i, err := blockchain.InsertChain(chain); err != nil {
  822. t.Fatalf("failed to insert original chain[%d]: %v", i, err)
  823. }
  824. // overwrite the old chain
  825. chain, _ = GenerateChain(params.TestChainConfig, genesis, db, 5, func(i int, gen *BlockGen) {
  826. switch i {
  827. case 0:
  828. pastAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(signer, key3)
  829. gen.AddTx(pastAdd) // This transaction needs to be injected during reorg
  830. case 2:
  831. gen.AddTx(postponed) // This transaction was postponed from block #1 in the original chain
  832. gen.AddTx(swapped) // This transaction was swapped from the exact current spot in the original chain
  833. freshAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(signer, key3)
  834. gen.AddTx(freshAdd) // This transaction will be added exactly at reorg time
  835. case 3:
  836. futureAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(signer, key3)
  837. gen.AddTx(futureAdd) // This transaction will be added after a full reorg
  838. }
  839. })
  840. if _, err := blockchain.InsertChain(chain); err != nil {
  841. t.Fatalf("failed to insert forked chain: %v", err)
  842. }
  843. // removed tx
  844. for i, tx := range (types.Transactions{pastDrop, freshDrop}) {
  845. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn != nil {
  846. t.Errorf("drop %d: tx %v found while shouldn't have been", i, txn)
  847. }
  848. if GetReceipt(db, tx.Hash()) != nil {
  849. t.Errorf("drop %d: receipt found while shouldn't have been", i)
  850. }
  851. }
  852. // added tx
  853. for i, tx := range (types.Transactions{pastAdd, freshAdd, futureAdd}) {
  854. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn == nil {
  855. t.Errorf("add %d: expected tx to be found", i)
  856. }
  857. if GetReceipt(db, tx.Hash()) == nil {
  858. t.Errorf("add %d: expected receipt to be found", i)
  859. }
  860. }
  861. // shared tx
  862. for i, tx := range (types.Transactions{postponed, swapped}) {
  863. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn == nil {
  864. t.Errorf("share %d: expected tx to be found", i)
  865. }
  866. if GetReceipt(db, tx.Hash()) == nil {
  867. t.Errorf("share %d: expected receipt to be found", i)
  868. }
  869. }
  870. }
  871. func TestLogReorgs(t *testing.T) {
  872. params.MinGasLimit = big.NewInt(125000) // Minimum the gas limit may ever be.
  873. params.GenesisGasLimit = big.NewInt(3141592) // Gas limit of the Genesis block.
  874. var (
  875. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  876. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  877. db, _ = ethdb.NewMemDatabase()
  878. // this code generates a log
  879. code = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
  880. signer = types.NewEIP155Signer(big.NewInt(1))
  881. )
  882. genesis := WriteGenesisBlockForTesting(db,
  883. GenesisAccount{addr1, big.NewInt(10000000000000)},
  884. )
  885. evmux := &event.TypeMux{}
  886. blockchain, _ := NewBlockChain(db, testChainConfig(), FakePow{}, evmux)
  887. subs := evmux.Subscribe(RemovedLogsEvent{})
  888. chain, _ := GenerateChain(params.TestChainConfig, genesis, db, 2, func(i int, gen *BlockGen) {
  889. if i == 1 {
  890. tx, err := types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), big.NewInt(1000000), new(big.Int), code).SignECDSA(signer, key1)
  891. if err != nil {
  892. t.Fatalf("failed to create tx: %v", err)
  893. }
  894. gen.AddTx(tx)
  895. }
  896. })
  897. if _, err := blockchain.InsertChain(chain); err != nil {
  898. t.Fatalf("failed to insert chain: %v", err)
  899. }
  900. chain, _ = GenerateChain(params.TestChainConfig, genesis, db, 3, func(i int, gen *BlockGen) {})
  901. if _, err := blockchain.InsertChain(chain); err != nil {
  902. t.Fatalf("failed to insert forked chain: %v", err)
  903. }
  904. ev := <-subs.Chan()
  905. if len(ev.Data.(RemovedLogsEvent).Logs) == 0 {
  906. t.Error("expected logs")
  907. }
  908. }
  909. func TestReorgSideEvent(t *testing.T) {
  910. var (
  911. db, _ = ethdb.NewMemDatabase()
  912. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  913. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  914. genesis = WriteGenesisBlockForTesting(db, GenesisAccount{addr1, big.NewInt(10000000000000)})
  915. signer = types.NewEIP155Signer(big.NewInt(1))
  916. )
  917. evmux := &event.TypeMux{}
  918. blockchain, _ := NewBlockChain(db, testChainConfig(), FakePow{}, evmux)
  919. chain, _ := GenerateChain(params.TestChainConfig, genesis, db, 3, func(i int, gen *BlockGen) {})
  920. if _, err := blockchain.InsertChain(chain); err != nil {
  921. t.Fatalf("failed to insert chain: %v", err)
  922. }
  923. replacementBlocks, _ := GenerateChain(params.TestChainConfig, genesis, db, 4, func(i int, gen *BlockGen) {
  924. tx, err := types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), big.NewInt(1000000), new(big.Int), nil).SignECDSA(signer, key1)
  925. if i == 2 {
  926. gen.OffsetTime(-1)
  927. }
  928. if err != nil {
  929. t.Fatalf("failed to create tx: %v", err)
  930. }
  931. gen.AddTx(tx)
  932. })
  933. subs := evmux.Subscribe(ChainSideEvent{})
  934. if _, err := blockchain.InsertChain(replacementBlocks); err != nil {
  935. t.Fatalf("failed to insert chain: %v", err)
  936. }
  937. // first two block of the secondary chain are for a brief moment considered
  938. // side chains because up to that point the first one is considered the
  939. // heavier chain.
  940. expectedSideHashes := map[common.Hash]bool{
  941. replacementBlocks[0].Hash(): true,
  942. replacementBlocks[1].Hash(): true,
  943. chain[0].Hash(): true,
  944. chain[1].Hash(): true,
  945. chain[2].Hash(): true,
  946. }
  947. i := 0
  948. const timeoutDura = 10 * time.Second
  949. timeout := time.NewTimer(timeoutDura)
  950. done:
  951. for {
  952. select {
  953. case ev := <-subs.Chan():
  954. block := ev.Data.(ChainSideEvent).Block
  955. if _, ok := expectedSideHashes[block.Hash()]; !ok {
  956. t.Errorf("%d: didn't expect %x to be in side chain", i, block.Hash())
  957. }
  958. i++
  959. if i == len(expectedSideHashes) {
  960. timeout.Stop()
  961. break done
  962. }
  963. timeout.Reset(timeoutDura)
  964. case <-timeout.C:
  965. t.Fatal("Timeout. Possibly not all blocks were triggered for sideevent")
  966. }
  967. }
  968. // make sure no more events are fired
  969. select {
  970. case e := <-subs.Chan():
  971. t.Errorf("unexpected event fired: %v", e)
  972. case <-time.After(250 * time.Millisecond):
  973. }
  974. }
  975. // Tests if the canonical block can be fetched from the database during chain insertion.
  976. func TestCanonicalBlockRetrieval(t *testing.T) {
  977. var (
  978. db, _ = ethdb.NewMemDatabase()
  979. genesis = WriteGenesisBlockForTesting(db)
  980. )
  981. evmux := &event.TypeMux{}
  982. blockchain, _ := NewBlockChain(db, testChainConfig(), FakePow{}, evmux)
  983. chain, _ := GenerateChain(params.TestChainConfig, genesis, db, 10, func(i int, gen *BlockGen) {})
  984. for i, _ := range chain {
  985. go func(block *types.Block) {
  986. // try to retrieve a block by its canonical hash and see if the block data can be retrieved.
  987. for {
  988. ch := GetCanonicalHash(db, block.NumberU64())
  989. if ch == (common.Hash{}) {
  990. continue // busy wait for canonical hash to be written
  991. }
  992. if ch != block.Hash() {
  993. t.Fatalf("unknown canonical hash, want %s, got %s", block.Hash().Hex(), ch.Hex())
  994. }
  995. fb := GetBlock(db, ch, block.NumberU64())
  996. if fb == nil {
  997. t.Fatalf("unable to retrieve block %d for canonical hash: %s", block.NumberU64(), ch.Hex())
  998. }
  999. if fb.Hash() != block.Hash() {
  1000. t.Fatalf("invalid block hash for block %d, want %s, got %s", block.NumberU64(), block.Hash().Hex(), fb.Hash().Hex())
  1001. }
  1002. return
  1003. }
  1004. }(chain[i])
  1005. blockchain.InsertChain(types.Blocks{chain[i]})
  1006. }
  1007. }
  1008. func TestEIP155Transition(t *testing.T) {
  1009. // Configure and generate a sample block chain
  1010. var (
  1011. db, _ = ethdb.NewMemDatabase()
  1012. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1013. address = crypto.PubkeyToAddress(key.PublicKey)
  1014. funds = big.NewInt(1000000000)
  1015. deleteAddr = common.Address{1}
  1016. genesis = WriteGenesisBlockForTesting(db, GenesisAccount{address, funds}, GenesisAccount{deleteAddr, new(big.Int)})
  1017. config = &params.ChainConfig{ChainId: big.NewInt(1), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)}
  1018. mux event.TypeMux
  1019. )
  1020. blockchain, _ := NewBlockChain(db, config, FakePow{}, &mux)
  1021. blocks, _ := GenerateChain(config, genesis, db, 4, func(i int, block *BlockGen) {
  1022. var (
  1023. tx *types.Transaction
  1024. err error
  1025. basicTx = func(signer types.Signer) (*types.Transaction, error) {
  1026. return types.NewTransaction(block.TxNonce(address), common.Address{}, new(big.Int), big.NewInt(21000), new(big.Int), nil).SignECDSA(signer, key)
  1027. }
  1028. )
  1029. switch i {
  1030. case 0:
  1031. tx, err = basicTx(types.HomesteadSigner{})
  1032. if err != nil {
  1033. t.Fatal(err)
  1034. }
  1035. block.AddTx(tx)
  1036. case 2:
  1037. tx, err = basicTx(types.HomesteadSigner{})
  1038. if err != nil {
  1039. t.Fatal(err)
  1040. }
  1041. block.AddTx(tx)
  1042. tx, err = basicTx(types.NewEIP155Signer(config.ChainId))
  1043. if err != nil {
  1044. t.Fatal(err)
  1045. }
  1046. block.AddTx(tx)
  1047. case 3:
  1048. tx, err = basicTx(types.HomesteadSigner{})
  1049. if err != nil {
  1050. t.Fatal(err)
  1051. }
  1052. block.AddTx(tx)
  1053. tx, err = basicTx(types.NewEIP155Signer(config.ChainId))
  1054. if err != nil {
  1055. t.Fatal(err)
  1056. }
  1057. block.AddTx(tx)
  1058. }
  1059. })
  1060. if _, err := blockchain.InsertChain(blocks); err != nil {
  1061. t.Fatal(err)
  1062. }
  1063. block := blockchain.GetBlockByNumber(1)
  1064. if block.Transactions()[0].Protected() {
  1065. t.Error("Expected block[0].txs[0] to not be replay protected")
  1066. }
  1067. block = blockchain.GetBlockByNumber(3)
  1068. if block.Transactions()[0].Protected() {
  1069. t.Error("Expected block[3].txs[0] to not be replay protected")
  1070. }
  1071. if !block.Transactions()[1].Protected() {
  1072. t.Error("Expected block[3].txs[1] to be replay protected")
  1073. }
  1074. if _, err := blockchain.InsertChain(blocks[4:]); err != nil {
  1075. t.Fatal(err)
  1076. }
  1077. // generate an invalid chain id transaction
  1078. config = &params.ChainConfig{ChainId: big.NewInt(2), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)}
  1079. blocks, _ = GenerateChain(config, blocks[len(blocks)-1], db, 4, func(i int, block *BlockGen) {
  1080. var (
  1081. tx *types.Transaction
  1082. err error
  1083. basicTx = func(signer types.Signer) (*types.Transaction, error) {
  1084. return types.NewTransaction(block.TxNonce(address), common.Address{}, new(big.Int), big.NewInt(21000), new(big.Int), nil).SignECDSA(signer, key)
  1085. }
  1086. )
  1087. switch i {
  1088. case 0:
  1089. tx, err = basicTx(types.NewEIP155Signer(big.NewInt(2)))
  1090. if err != nil {
  1091. t.Fatal(err)
  1092. }
  1093. block.AddTx(tx)
  1094. }
  1095. })
  1096. _, err := blockchain.InsertChain(blocks)
  1097. if err != types.ErrInvalidChainId {
  1098. t.Error("expected error:", types.ErrInvalidChainId)
  1099. }
  1100. }
  1101. func TestEIP161AccountRemoval(t *testing.T) {
  1102. // Configure and generate a sample block chain
  1103. var (
  1104. db, _ = ethdb.NewMemDatabase()
  1105. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1106. address = crypto.PubkeyToAddress(key.PublicKey)
  1107. funds = big.NewInt(1000000000)
  1108. theAddr = common.Address{1}
  1109. genesis = WriteGenesisBlockForTesting(db, GenesisAccount{address, funds})
  1110. config = &params.ChainConfig{
  1111. ChainId: big.NewInt(1),
  1112. HomesteadBlock: new(big.Int),
  1113. EIP155Block: new(big.Int),
  1114. EIP158Block: big.NewInt(2),
  1115. }
  1116. mux event.TypeMux
  1117. blockchain, _ = NewBlockChain(db, config, FakePow{}, &mux)
  1118. )
  1119. blocks, _ := GenerateChain(config, genesis, db, 3, func(i int, block *BlockGen) {
  1120. var (
  1121. tx *types.Transaction
  1122. err error
  1123. signer = types.NewEIP155Signer(config.ChainId)
  1124. )
  1125. switch i {
  1126. case 0:
  1127. tx, err = types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), big.NewInt(21000), new(big.Int), nil).SignECDSA(signer, key)
  1128. case 1:
  1129. tx, err = types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), big.NewInt(21000), new(big.Int), nil).SignECDSA(signer, key)
  1130. case 2:
  1131. tx, err = types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), big.NewInt(21000), new(big.Int), nil).SignECDSA(signer, key)
  1132. }
  1133. if err != nil {
  1134. t.Fatal(err)
  1135. }
  1136. block.AddTx(tx)
  1137. })
  1138. // account must exist pre eip 161
  1139. if _, err := blockchain.InsertChain(types.Blocks{blocks[0]}); err != nil {
  1140. t.Fatal(err)
  1141. }
  1142. if !blockchain.stateCache.Exist(theAddr) {
  1143. t.Error("expected account to exist")
  1144. }
  1145. // account needs to be deleted post eip 161
  1146. if _, err := blockchain.InsertChain(types.Blocks{blocks[1]}); err != nil {
  1147. t.Fatal(err)
  1148. }
  1149. if blockchain.stateCache.Exist(theAddr) {
  1150. t.Error("account should not expect")
  1151. }
  1152. // account musn't be created post eip 161
  1153. if _, err := blockchain.InsertChain(types.Blocks{blocks[2]}); err != nil {
  1154. t.Fatal(err)
  1155. }
  1156. if blockchain.stateCache.Exist(theAddr) {
  1157. t.Error("account should not expect")
  1158. }
  1159. }