blockchain_test.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  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. "sync"
  22. "testing"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/consensus/ethash"
  26. "github.com/ethereum/go-ethereum/core/rawdb"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/core/vm"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. "github.com/ethereum/go-ethereum/ethdb"
  32. "github.com/ethereum/go-ethereum/params"
  33. )
  34. // Test fork of length N starting from block i
  35. func testFork(t *testing.T, blockchain *BlockChain, i, n int, full bool, comparator func(td1, td2 *big.Int)) {
  36. // Copy old chain up to #i into a new db
  37. db, blockchain2, err := newCanonical(ethash.NewFaker(), i, full)
  38. if err != nil {
  39. t.Fatal("could not make new canonical in testFork", err)
  40. }
  41. defer blockchain2.Stop()
  42. // Assert the chains have the same header/block at #i
  43. var hash1, hash2 common.Hash
  44. if full {
  45. hash1 = blockchain.GetBlockByNumber(uint64(i)).Hash()
  46. hash2 = blockchain2.GetBlockByNumber(uint64(i)).Hash()
  47. } else {
  48. hash1 = blockchain.GetHeaderByNumber(uint64(i)).Hash()
  49. hash2 = blockchain2.GetHeaderByNumber(uint64(i)).Hash()
  50. }
  51. if hash1 != hash2 {
  52. t.Errorf("chain content mismatch at %d: have hash %v, want hash %v", i, hash2, hash1)
  53. }
  54. // Extend the newly created chain
  55. var (
  56. blockChainB []*types.Block
  57. headerChainB []*types.Header
  58. )
  59. if full {
  60. blockChainB = makeBlockChain(blockchain2.CurrentBlock(), n, ethash.NewFaker(), db, forkSeed)
  61. if _, err := blockchain2.InsertChain(blockChainB); err != nil {
  62. t.Fatalf("failed to insert forking chain: %v", err)
  63. }
  64. } else {
  65. headerChainB = makeHeaderChain(blockchain2.CurrentHeader(), n, ethash.NewFaker(), db, forkSeed)
  66. if _, err := blockchain2.InsertHeaderChain(headerChainB, 1); err != nil {
  67. t.Fatalf("failed to insert forking chain: %v", err)
  68. }
  69. }
  70. // Sanity check that the forked chain can be imported into the original
  71. var tdPre, tdPost *big.Int
  72. if full {
  73. tdPre = blockchain.GetTdByHash(blockchain.CurrentBlock().Hash())
  74. if err := testBlockChainImport(blockChainB, blockchain); err != nil {
  75. t.Fatalf("failed to import forked block chain: %v", err)
  76. }
  77. tdPost = blockchain.GetTdByHash(blockChainB[len(blockChainB)-1].Hash())
  78. } else {
  79. tdPre = blockchain.GetTdByHash(blockchain.CurrentHeader().Hash())
  80. if err := testHeaderChainImport(headerChainB, blockchain); err != nil {
  81. t.Fatalf("failed to import forked header chain: %v", err)
  82. }
  83. tdPost = blockchain.GetTdByHash(headerChainB[len(headerChainB)-1].Hash())
  84. }
  85. // Compare the total difficulties of the chains
  86. comparator(tdPre, tdPost)
  87. }
  88. func printChain(bc *BlockChain) {
  89. for i := bc.CurrentBlock().Number().Uint64(); i > 0; i-- {
  90. b := bc.GetBlockByNumber(uint64(i))
  91. fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty())
  92. }
  93. }
  94. // testBlockChainImport tries to process a chain of blocks, writing them into
  95. // the database if successful.
  96. func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error {
  97. for _, block := range chain {
  98. // Try and process the block
  99. err := blockchain.engine.VerifyHeader(blockchain, block.Header(), true)
  100. if err == nil {
  101. err = blockchain.validator.ValidateBody(block)
  102. }
  103. if err != nil {
  104. if err == ErrKnownBlock {
  105. continue
  106. }
  107. return err
  108. }
  109. statedb, err := state.New(blockchain.GetBlockByHash(block.ParentHash()).Root(), blockchain.stateCache)
  110. if err != nil {
  111. return err
  112. }
  113. receipts, _, usedGas, err := blockchain.Processor().Process(block, statedb, vm.Config{})
  114. if err != nil {
  115. blockchain.reportBlock(block, receipts, err)
  116. return err
  117. }
  118. err = blockchain.validator.ValidateState(block, blockchain.GetBlockByHash(block.ParentHash()), statedb, receipts, usedGas)
  119. if err != nil {
  120. blockchain.reportBlock(block, receipts, err)
  121. return err
  122. }
  123. blockchain.mu.Lock()
  124. rawdb.WriteTd(blockchain.db, block.Hash(), block.NumberU64(), new(big.Int).Add(block.Difficulty(), blockchain.GetTdByHash(block.ParentHash())))
  125. rawdb.WriteBlock(blockchain.db, block)
  126. statedb.Commit(false)
  127. blockchain.mu.Unlock()
  128. }
  129. return nil
  130. }
  131. // testHeaderChainImport tries to process a chain of header, writing them into
  132. // the database if successful.
  133. func testHeaderChainImport(chain []*types.Header, blockchain *BlockChain) error {
  134. for _, header := range chain {
  135. // Try and validate the header
  136. if err := blockchain.engine.VerifyHeader(blockchain, header, false); err != nil {
  137. return err
  138. }
  139. // Manually insert the header into the database, but don't reorganise (allows subsequent testing)
  140. blockchain.mu.Lock()
  141. rawdb.WriteTd(blockchain.db, header.Hash(), header.Number.Uint64(), new(big.Int).Add(header.Difficulty, blockchain.GetTdByHash(header.ParentHash)))
  142. rawdb.WriteHeader(blockchain.db, header)
  143. blockchain.mu.Unlock()
  144. }
  145. return nil
  146. }
  147. func insertChain(done chan bool, blockchain *BlockChain, chain types.Blocks, t *testing.T) {
  148. _, err := blockchain.InsertChain(chain)
  149. if err != nil {
  150. fmt.Println(err)
  151. t.FailNow()
  152. }
  153. done <- true
  154. }
  155. func TestLastBlock(t *testing.T) {
  156. _, blockchain, err := newCanonical(ethash.NewFaker(), 0, true)
  157. if err != nil {
  158. t.Fatalf("failed to create pristine chain: %v", err)
  159. }
  160. defer blockchain.Stop()
  161. blocks := makeBlockChain(blockchain.CurrentBlock(), 1, ethash.NewFullFaker(), blockchain.db, 0)
  162. if _, err := blockchain.InsertChain(blocks); err != nil {
  163. t.Fatalf("Failed to insert block: %v", err)
  164. }
  165. if blocks[len(blocks)-1].Hash() != rawdb.ReadHeadBlockHash(blockchain.db) {
  166. t.Fatalf("Write/Get HeadBlockHash failed")
  167. }
  168. }
  169. // Tests that given a starting canonical chain of a given size, it can be extended
  170. // with various length chains.
  171. func TestExtendCanonicalHeaders(t *testing.T) { testExtendCanonical(t, false) }
  172. func TestExtendCanonicalBlocks(t *testing.T) { testExtendCanonical(t, true) }
  173. func testExtendCanonical(t *testing.T, full bool) {
  174. length := 5
  175. // Make first chain starting from genesis
  176. _, processor, err := newCanonical(ethash.NewFaker(), length, full)
  177. if err != nil {
  178. t.Fatalf("failed to make new canonical chain: %v", err)
  179. }
  180. defer processor.Stop()
  181. // Define the difficulty comparator
  182. better := func(td1, td2 *big.Int) {
  183. if td2.Cmp(td1) <= 0 {
  184. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  185. }
  186. }
  187. // Start fork from current height
  188. testFork(t, processor, length, 1, full, better)
  189. testFork(t, processor, length, 2, full, better)
  190. testFork(t, processor, length, 5, full, better)
  191. testFork(t, processor, length, 10, full, better)
  192. }
  193. // Tests that given a starting canonical chain of a given size, creating shorter
  194. // forks do not take canonical ownership.
  195. func TestShorterForkHeaders(t *testing.T) { testShorterFork(t, false) }
  196. func TestShorterForkBlocks(t *testing.T) { testShorterFork(t, true) }
  197. func testShorterFork(t *testing.T, full bool) {
  198. length := 10
  199. // Make first chain starting from genesis
  200. _, processor, err := newCanonical(ethash.NewFaker(), length, full)
  201. if err != nil {
  202. t.Fatalf("failed to make new canonical chain: %v", err)
  203. }
  204. defer processor.Stop()
  205. // Define the difficulty comparator
  206. worse := func(td1, td2 *big.Int) {
  207. if td2.Cmp(td1) >= 0 {
  208. t.Errorf("total difficulty mismatch: have %v, expected less than %v", td2, td1)
  209. }
  210. }
  211. // Sum of numbers must be less than `length` for this to be a shorter fork
  212. testFork(t, processor, 0, 3, full, worse)
  213. testFork(t, processor, 0, 7, full, worse)
  214. testFork(t, processor, 1, 1, full, worse)
  215. testFork(t, processor, 1, 7, full, worse)
  216. testFork(t, processor, 5, 3, full, worse)
  217. testFork(t, processor, 5, 4, full, worse)
  218. }
  219. // Tests that given a starting canonical chain of a given size, creating longer
  220. // forks do take canonical ownership.
  221. func TestLongerForkHeaders(t *testing.T) { testLongerFork(t, false) }
  222. func TestLongerForkBlocks(t *testing.T) { testLongerFork(t, true) }
  223. func testLongerFork(t *testing.T, full bool) {
  224. length := 10
  225. // Make first chain starting from genesis
  226. _, processor, err := newCanonical(ethash.NewFaker(), length, full)
  227. if err != nil {
  228. t.Fatalf("failed to make new canonical chain: %v", err)
  229. }
  230. defer processor.Stop()
  231. // Define the difficulty comparator
  232. better := func(td1, td2 *big.Int) {
  233. if td2.Cmp(td1) <= 0 {
  234. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  235. }
  236. }
  237. // Sum of numbers must be greater than `length` for this to be a longer fork
  238. testFork(t, processor, 0, 11, full, better)
  239. testFork(t, processor, 0, 15, full, better)
  240. testFork(t, processor, 1, 10, full, better)
  241. testFork(t, processor, 1, 12, full, better)
  242. testFork(t, processor, 5, 6, full, better)
  243. testFork(t, processor, 5, 8, full, better)
  244. }
  245. // Tests that given a starting canonical chain of a given size, creating equal
  246. // forks do take canonical ownership.
  247. func TestEqualForkHeaders(t *testing.T) { testEqualFork(t, false) }
  248. func TestEqualForkBlocks(t *testing.T) { testEqualFork(t, true) }
  249. func testEqualFork(t *testing.T, full bool) {
  250. length := 10
  251. // Make first chain starting from genesis
  252. _, processor, err := newCanonical(ethash.NewFaker(), length, full)
  253. if err != nil {
  254. t.Fatalf("failed to make new canonical chain: %v", err)
  255. }
  256. defer processor.Stop()
  257. // Define the difficulty comparator
  258. equal := func(td1, td2 *big.Int) {
  259. if td2.Cmp(td1) != 0 {
  260. t.Errorf("total difficulty mismatch: have %v, want %v", td2, td1)
  261. }
  262. }
  263. // Sum of numbers must be equal to `length` for this to be an equal fork
  264. testFork(t, processor, 0, 10, full, equal)
  265. testFork(t, processor, 1, 9, full, equal)
  266. testFork(t, processor, 2, 8, full, equal)
  267. testFork(t, processor, 5, 5, full, equal)
  268. testFork(t, processor, 6, 4, full, equal)
  269. testFork(t, processor, 9, 1, full, equal)
  270. }
  271. // Tests that chains missing links do not get accepted by the processor.
  272. func TestBrokenHeaderChain(t *testing.T) { testBrokenChain(t, false) }
  273. func TestBrokenBlockChain(t *testing.T) { testBrokenChain(t, true) }
  274. func testBrokenChain(t *testing.T, full bool) {
  275. // Make chain starting from genesis
  276. db, blockchain, err := newCanonical(ethash.NewFaker(), 10, full)
  277. if err != nil {
  278. t.Fatalf("failed to make new canonical chain: %v", err)
  279. }
  280. defer blockchain.Stop()
  281. // Create a forked chain, and try to insert with a missing link
  282. if full {
  283. chain := makeBlockChain(blockchain.CurrentBlock(), 5, ethash.NewFaker(), db, forkSeed)[1:]
  284. if err := testBlockChainImport(chain, blockchain); err == nil {
  285. t.Errorf("broken block chain not reported")
  286. }
  287. } else {
  288. chain := makeHeaderChain(blockchain.CurrentHeader(), 5, ethash.NewFaker(), db, forkSeed)[1:]
  289. if err := testHeaderChainImport(chain, blockchain); err == nil {
  290. t.Errorf("broken header chain not reported")
  291. }
  292. }
  293. }
  294. // Tests that reorganising a long difficult chain after a short easy one
  295. // overwrites the canonical numbers and links in the database.
  296. func TestReorgLongHeaders(t *testing.T) { testReorgLong(t, false) }
  297. func TestReorgLongBlocks(t *testing.T) { testReorgLong(t, true) }
  298. func testReorgLong(t *testing.T, full bool) {
  299. testReorg(t, []int64{0, 0, -9}, []int64{0, 0, 0, -9}, 393280, full)
  300. }
  301. // Tests that reorganising a short difficult chain after a long easy one
  302. // overwrites the canonical numbers and links in the database.
  303. func TestReorgShortHeaders(t *testing.T) { testReorgShort(t, false) }
  304. func TestReorgShortBlocks(t *testing.T) { testReorgShort(t, true) }
  305. func testReorgShort(t *testing.T, full bool) {
  306. // Create a long easy chain vs. a short heavy one. Due to difficulty adjustment
  307. // we need a fairly long chain of blocks with different difficulties for a short
  308. // one to become heavyer than a long one. The 96 is an empirical value.
  309. easy := make([]int64, 96)
  310. for i := 0; i < len(easy); i++ {
  311. easy[i] = 60
  312. }
  313. diff := make([]int64, len(easy)-1)
  314. for i := 0; i < len(diff); i++ {
  315. diff[i] = -9
  316. }
  317. testReorg(t, easy, diff, 12615120, full)
  318. }
  319. func testReorg(t *testing.T, first, second []int64, td int64, full bool) {
  320. // Create a pristine chain and database
  321. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full)
  322. if err != nil {
  323. t.Fatalf("failed to create pristine chain: %v", err)
  324. }
  325. defer blockchain.Stop()
  326. // Insert an easy and a difficult chain afterwards
  327. easyBlocks, _ := GenerateChain(params.TestChainConfig, blockchain.CurrentBlock(), ethash.NewFaker(), db, len(first), func(i int, b *BlockGen) {
  328. b.OffsetTime(first[i])
  329. })
  330. diffBlocks, _ := GenerateChain(params.TestChainConfig, blockchain.CurrentBlock(), ethash.NewFaker(), db, len(second), func(i int, b *BlockGen) {
  331. b.OffsetTime(second[i])
  332. })
  333. if full {
  334. if _, err := blockchain.InsertChain(easyBlocks); err != nil {
  335. t.Fatalf("failed to insert easy chain: %v", err)
  336. }
  337. if _, err := blockchain.InsertChain(diffBlocks); err != nil {
  338. t.Fatalf("failed to insert difficult chain: %v", err)
  339. }
  340. } else {
  341. easyHeaders := make([]*types.Header, len(easyBlocks))
  342. for i, block := range easyBlocks {
  343. easyHeaders[i] = block.Header()
  344. }
  345. diffHeaders := make([]*types.Header, len(diffBlocks))
  346. for i, block := range diffBlocks {
  347. diffHeaders[i] = block.Header()
  348. }
  349. if _, err := blockchain.InsertHeaderChain(easyHeaders, 1); err != nil {
  350. t.Fatalf("failed to insert easy chain: %v", err)
  351. }
  352. if _, err := blockchain.InsertHeaderChain(diffHeaders, 1); err != nil {
  353. t.Fatalf("failed to insert difficult chain: %v", err)
  354. }
  355. }
  356. // Check that the chain is valid number and link wise
  357. if full {
  358. prev := blockchain.CurrentBlock()
  359. for block := blockchain.GetBlockByNumber(blockchain.CurrentBlock().NumberU64() - 1); block.NumberU64() != 0; prev, block = block, blockchain.GetBlockByNumber(block.NumberU64()-1) {
  360. if prev.ParentHash() != block.Hash() {
  361. t.Errorf("parent block hash mismatch: have %x, want %x", prev.ParentHash(), block.Hash())
  362. }
  363. }
  364. } else {
  365. prev := blockchain.CurrentHeader()
  366. for header := blockchain.GetHeaderByNumber(blockchain.CurrentHeader().Number.Uint64() - 1); header.Number.Uint64() != 0; prev, header = header, blockchain.GetHeaderByNumber(header.Number.Uint64()-1) {
  367. if prev.ParentHash != header.Hash() {
  368. t.Errorf("parent header hash mismatch: have %x, want %x", prev.ParentHash, header.Hash())
  369. }
  370. }
  371. }
  372. // Make sure the chain total difficulty is the correct one
  373. want := new(big.Int).Add(blockchain.genesisBlock.Difficulty(), big.NewInt(td))
  374. if full {
  375. if have := blockchain.GetTdByHash(blockchain.CurrentBlock().Hash()); have.Cmp(want) != 0 {
  376. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  377. }
  378. } else {
  379. if have := blockchain.GetTdByHash(blockchain.CurrentHeader().Hash()); have.Cmp(want) != 0 {
  380. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  381. }
  382. }
  383. }
  384. // Tests that the insertion functions detect banned hashes.
  385. func TestBadHeaderHashes(t *testing.T) { testBadHashes(t, false) }
  386. func TestBadBlockHashes(t *testing.T) { testBadHashes(t, true) }
  387. func testBadHashes(t *testing.T, full bool) {
  388. // Create a pristine chain and database
  389. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full)
  390. if err != nil {
  391. t.Fatalf("failed to create pristine chain: %v", err)
  392. }
  393. defer blockchain.Stop()
  394. // Create a chain, ban a hash and try to import
  395. if full {
  396. blocks := makeBlockChain(blockchain.CurrentBlock(), 3, ethash.NewFaker(), db, 10)
  397. BadHashes[blocks[2].Header().Hash()] = true
  398. defer func() { delete(BadHashes, blocks[2].Header().Hash()) }()
  399. _, err = blockchain.InsertChain(blocks)
  400. } else {
  401. headers := makeHeaderChain(blockchain.CurrentHeader(), 3, ethash.NewFaker(), db, 10)
  402. BadHashes[headers[2].Hash()] = true
  403. defer func() { delete(BadHashes, headers[2].Hash()) }()
  404. _, err = blockchain.InsertHeaderChain(headers, 1)
  405. }
  406. if err != ErrBlacklistedHash {
  407. t.Errorf("error mismatch: have: %v, want: %v", err, ErrBlacklistedHash)
  408. }
  409. }
  410. // Tests that bad hashes are detected on boot, and the chain rolled back to a
  411. // good state prior to the bad hash.
  412. func TestReorgBadHeaderHashes(t *testing.T) { testReorgBadHashes(t, false) }
  413. func TestReorgBadBlockHashes(t *testing.T) { testReorgBadHashes(t, true) }
  414. func testReorgBadHashes(t *testing.T, full bool) {
  415. // Create a pristine chain and database
  416. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full)
  417. if err != nil {
  418. t.Fatalf("failed to create pristine chain: %v", err)
  419. }
  420. // Create a chain, import and ban afterwards
  421. headers := makeHeaderChain(blockchain.CurrentHeader(), 4, ethash.NewFaker(), db, 10)
  422. blocks := makeBlockChain(blockchain.CurrentBlock(), 4, ethash.NewFaker(), db, 10)
  423. if full {
  424. if _, err = blockchain.InsertChain(blocks); err != nil {
  425. t.Errorf("failed to import blocks: %v", err)
  426. }
  427. if blockchain.CurrentBlock().Hash() != blocks[3].Hash() {
  428. t.Errorf("last block hash mismatch: have: %x, want %x", blockchain.CurrentBlock().Hash(), blocks[3].Header().Hash())
  429. }
  430. BadHashes[blocks[3].Header().Hash()] = true
  431. defer func() { delete(BadHashes, blocks[3].Header().Hash()) }()
  432. } else {
  433. if _, err = blockchain.InsertHeaderChain(headers, 1); err != nil {
  434. t.Errorf("failed to import headers: %v", err)
  435. }
  436. if blockchain.CurrentHeader().Hash() != headers[3].Hash() {
  437. t.Errorf("last header hash mismatch: have: %x, want %x", blockchain.CurrentHeader().Hash(), headers[3].Hash())
  438. }
  439. BadHashes[headers[3].Hash()] = true
  440. defer func() { delete(BadHashes, headers[3].Hash()) }()
  441. }
  442. blockchain.Stop()
  443. // Create a new BlockChain and check that it rolled back the state.
  444. ncm, err := NewBlockChain(blockchain.db, nil, blockchain.chainConfig, ethash.NewFaker(), vm.Config{})
  445. if err != nil {
  446. t.Fatalf("failed to create new chain manager: %v", err)
  447. }
  448. if full {
  449. if ncm.CurrentBlock().Hash() != blocks[2].Header().Hash() {
  450. t.Errorf("last block hash mismatch: have: %x, want %x", ncm.CurrentBlock().Hash(), blocks[2].Header().Hash())
  451. }
  452. if blocks[2].Header().GasLimit != ncm.GasLimit() {
  453. t.Errorf("last block gasLimit mismatch: have: %d, want %d", ncm.GasLimit(), blocks[2].Header().GasLimit)
  454. }
  455. } else {
  456. if ncm.CurrentHeader().Hash() != headers[2].Hash() {
  457. t.Errorf("last header hash mismatch: have: %x, want %x", ncm.CurrentHeader().Hash(), headers[2].Hash())
  458. }
  459. }
  460. ncm.Stop()
  461. }
  462. // Tests chain insertions in the face of one entity containing an invalid nonce.
  463. func TestHeadersInsertNonceError(t *testing.T) { testInsertNonceError(t, false) }
  464. func TestBlocksInsertNonceError(t *testing.T) { testInsertNonceError(t, true) }
  465. func testInsertNonceError(t *testing.T, full bool) {
  466. for i := 1; i < 25 && !t.Failed(); i++ {
  467. // Create a pristine chain and database
  468. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full)
  469. if err != nil {
  470. t.Fatalf("failed to create pristine chain: %v", err)
  471. }
  472. defer blockchain.Stop()
  473. // Create and insert a chain with a failing nonce
  474. var (
  475. failAt int
  476. failRes int
  477. failNum uint64
  478. )
  479. if full {
  480. blocks := makeBlockChain(blockchain.CurrentBlock(), i, ethash.NewFaker(), db, 0)
  481. failAt = rand.Int() % len(blocks)
  482. failNum = blocks[failAt].NumberU64()
  483. blockchain.engine = ethash.NewFakeFailer(failNum)
  484. failRes, err = blockchain.InsertChain(blocks)
  485. } else {
  486. headers := makeHeaderChain(blockchain.CurrentHeader(), i, ethash.NewFaker(), db, 0)
  487. failAt = rand.Int() % len(headers)
  488. failNum = headers[failAt].Number.Uint64()
  489. blockchain.engine = ethash.NewFakeFailer(failNum)
  490. blockchain.hc.engine = blockchain.engine
  491. failRes, err = blockchain.InsertHeaderChain(headers, 1)
  492. }
  493. // Check that the returned error indicates the failure.
  494. if failRes != failAt {
  495. t.Errorf("test %d: failure index mismatch: have %d, want %d", i, failRes, failAt)
  496. }
  497. // Check that all no blocks after the failing block have been inserted.
  498. for j := 0; j < i-failAt; j++ {
  499. if full {
  500. if block := blockchain.GetBlockByNumber(failNum + uint64(j)); block != nil {
  501. t.Errorf("test %d: invalid block in chain: %v", i, block)
  502. }
  503. } else {
  504. if header := blockchain.GetHeaderByNumber(failNum + uint64(j)); header != nil {
  505. t.Errorf("test %d: invalid header in chain: %v", i, header)
  506. }
  507. }
  508. }
  509. }
  510. }
  511. // Tests that fast importing a block chain produces the same chain data as the
  512. // classical full block processing.
  513. func TestFastVsFullChains(t *testing.T) {
  514. // Configure and generate a sample block chain
  515. var (
  516. gendb = ethdb.NewMemDatabase()
  517. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  518. address = crypto.PubkeyToAddress(key.PublicKey)
  519. funds = big.NewInt(1000000000)
  520. gspec = &Genesis{
  521. Config: params.TestChainConfig,
  522. Alloc: GenesisAlloc{address: {Balance: funds}},
  523. }
  524. genesis = gspec.MustCommit(gendb)
  525. signer = types.NewEIP155Signer(gspec.Config.ChainId)
  526. )
  527. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, 1024, func(i int, block *BlockGen) {
  528. block.SetCoinbase(common.Address{0x00})
  529. // If the block number is multiple of 3, send a few bonus transactions to the miner
  530. if i%3 == 2 {
  531. for j := 0; j < i%4+1; j++ {
  532. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, nil, nil), signer, key)
  533. if err != nil {
  534. panic(err)
  535. }
  536. block.AddTx(tx)
  537. }
  538. }
  539. // If the block number is a multiple of 5, add a few bonus uncles to the block
  540. if i%5 == 5 {
  541. block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
  542. }
  543. })
  544. // Import the chain as an archive node for the comparison baseline
  545. archiveDb := ethdb.NewMemDatabase()
  546. gspec.MustCommit(archiveDb)
  547. archive, _ := NewBlockChain(archiveDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  548. defer archive.Stop()
  549. if n, err := archive.InsertChain(blocks); err != nil {
  550. t.Fatalf("failed to process block %d: %v", n, err)
  551. }
  552. // Fast import the chain as a non-archive node to test
  553. fastDb := ethdb.NewMemDatabase()
  554. gspec.MustCommit(fastDb)
  555. fast, _ := NewBlockChain(fastDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  556. defer fast.Stop()
  557. headers := make([]*types.Header, len(blocks))
  558. for i, block := range blocks {
  559. headers[i] = block.Header()
  560. }
  561. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  562. t.Fatalf("failed to insert header %d: %v", n, err)
  563. }
  564. if n, err := fast.InsertReceiptChain(blocks, receipts); err != nil {
  565. t.Fatalf("failed to insert receipt %d: %v", n, err)
  566. }
  567. // Iterate over all chain data components, and cross reference
  568. for i := 0; i < len(blocks); i++ {
  569. num, hash := blocks[i].NumberU64(), blocks[i].Hash()
  570. if ftd, atd := fast.GetTdByHash(hash), archive.GetTdByHash(hash); ftd.Cmp(atd) != 0 {
  571. t.Errorf("block #%d [%x]: td mismatch: have %v, want %v", num, hash, ftd, atd)
  572. }
  573. if fheader, aheader := fast.GetHeaderByHash(hash), archive.GetHeaderByHash(hash); fheader.Hash() != aheader.Hash() {
  574. t.Errorf("block #%d [%x]: header mismatch: have %v, want %v", num, hash, fheader, aheader)
  575. }
  576. if fblock, ablock := fast.GetBlockByHash(hash), archive.GetBlockByHash(hash); fblock.Hash() != ablock.Hash() {
  577. t.Errorf("block #%d [%x]: block mismatch: have %v, want %v", num, hash, fblock, ablock)
  578. } else if types.DeriveSha(fblock.Transactions()) != types.DeriveSha(ablock.Transactions()) {
  579. t.Errorf("block #%d [%x]: transactions mismatch: have %v, want %v", num, hash, fblock.Transactions(), ablock.Transactions())
  580. } else if types.CalcUncleHash(fblock.Uncles()) != types.CalcUncleHash(ablock.Uncles()) {
  581. t.Errorf("block #%d [%x]: uncles mismatch: have %v, want %v", num, hash, fblock.Uncles(), ablock.Uncles())
  582. }
  583. if freceipts, areceipts := rawdb.ReadReceipts(fastDb, hash, *rawdb.ReadHeaderNumber(fastDb, hash)), rawdb.ReadReceipts(archiveDb, hash, *rawdb.ReadHeaderNumber(archiveDb, hash)); types.DeriveSha(freceipts) != types.DeriveSha(areceipts) {
  584. t.Errorf("block #%d [%x]: receipts mismatch: have %v, want %v", num, hash, freceipts, areceipts)
  585. }
  586. }
  587. // Check that the canonical chains are the same between the databases
  588. for i := 0; i < len(blocks)+1; i++ {
  589. if fhash, ahash := rawdb.ReadCanonicalHash(fastDb, uint64(i)), rawdb.ReadCanonicalHash(archiveDb, uint64(i)); fhash != ahash {
  590. t.Errorf("block #%d: canonical hash mismatch: have %v, want %v", i, fhash, ahash)
  591. }
  592. }
  593. }
  594. // Tests that various import methods move the chain head pointers to the correct
  595. // positions.
  596. func TestLightVsFastVsFullChainHeads(t *testing.T) {
  597. // Configure and generate a sample block chain
  598. var (
  599. gendb = ethdb.NewMemDatabase()
  600. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  601. address = crypto.PubkeyToAddress(key.PublicKey)
  602. funds = big.NewInt(1000000000)
  603. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{address: {Balance: funds}}}
  604. genesis = gspec.MustCommit(gendb)
  605. )
  606. height := uint64(1024)
  607. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil)
  608. // Configure a subchain to roll back
  609. remove := []common.Hash{}
  610. for _, block := range blocks[height/2:] {
  611. remove = append(remove, block.Hash())
  612. }
  613. // Create a small assertion method to check the three heads
  614. assert := func(t *testing.T, kind string, chain *BlockChain, header uint64, fast uint64, block uint64) {
  615. if num := chain.CurrentBlock().NumberU64(); num != block {
  616. t.Errorf("%s head block mismatch: have #%v, want #%v", kind, num, block)
  617. }
  618. if num := chain.CurrentFastBlock().NumberU64(); num != fast {
  619. t.Errorf("%s head fast-block mismatch: have #%v, want #%v", kind, num, fast)
  620. }
  621. if num := chain.CurrentHeader().Number.Uint64(); num != header {
  622. t.Errorf("%s head header mismatch: have #%v, want #%v", kind, num, header)
  623. }
  624. }
  625. // Import the chain as an archive node and ensure all pointers are updated
  626. archiveDb := ethdb.NewMemDatabase()
  627. gspec.MustCommit(archiveDb)
  628. archive, _ := NewBlockChain(archiveDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  629. if n, err := archive.InsertChain(blocks); err != nil {
  630. t.Fatalf("failed to process block %d: %v", n, err)
  631. }
  632. defer archive.Stop()
  633. assert(t, "archive", archive, height, height, height)
  634. archive.Rollback(remove)
  635. assert(t, "archive", archive, height/2, height/2, height/2)
  636. // Import the chain as a non-archive node and ensure all pointers are updated
  637. fastDb := ethdb.NewMemDatabase()
  638. gspec.MustCommit(fastDb)
  639. fast, _ := NewBlockChain(fastDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  640. defer fast.Stop()
  641. headers := make([]*types.Header, len(blocks))
  642. for i, block := range blocks {
  643. headers[i] = block.Header()
  644. }
  645. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  646. t.Fatalf("failed to insert header %d: %v", n, err)
  647. }
  648. if n, err := fast.InsertReceiptChain(blocks, receipts); err != nil {
  649. t.Fatalf("failed to insert receipt %d: %v", n, err)
  650. }
  651. assert(t, "fast", fast, height, height, 0)
  652. fast.Rollback(remove)
  653. assert(t, "fast", fast, height/2, height/2, 0)
  654. // Import the chain as a light node and ensure all pointers are updated
  655. lightDb := ethdb.NewMemDatabase()
  656. gspec.MustCommit(lightDb)
  657. light, _ := NewBlockChain(lightDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  658. if n, err := light.InsertHeaderChain(headers, 1); err != nil {
  659. t.Fatalf("failed to insert header %d: %v", n, err)
  660. }
  661. defer light.Stop()
  662. assert(t, "light", light, height, 0, 0)
  663. light.Rollback(remove)
  664. assert(t, "light", light, height/2, 0, 0)
  665. }
  666. // Tests that chain reorganisations handle transaction removals and reinsertions.
  667. func TestChainTxReorgs(t *testing.T) {
  668. var (
  669. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  670. key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  671. key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  672. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  673. addr2 = crypto.PubkeyToAddress(key2.PublicKey)
  674. addr3 = crypto.PubkeyToAddress(key3.PublicKey)
  675. db = ethdb.NewMemDatabase()
  676. gspec = &Genesis{
  677. Config: params.TestChainConfig,
  678. GasLimit: 3141592,
  679. Alloc: GenesisAlloc{
  680. addr1: {Balance: big.NewInt(1000000)},
  681. addr2: {Balance: big.NewInt(1000000)},
  682. addr3: {Balance: big.NewInt(1000000)},
  683. },
  684. }
  685. genesis = gspec.MustCommit(db)
  686. signer = types.NewEIP155Signer(gspec.Config.ChainId)
  687. )
  688. // Create two transactions shared between the chains:
  689. // - postponed: transaction included at a later block in the forked chain
  690. // - swapped: transaction included at the same block number in the forked chain
  691. postponed, _ := types.SignTx(types.NewTransaction(0, addr1, big.NewInt(1000), params.TxGas, nil, nil), signer, key1)
  692. swapped, _ := types.SignTx(types.NewTransaction(1, addr1, big.NewInt(1000), params.TxGas, nil, nil), signer, key1)
  693. // Create two transactions that will be dropped by the forked chain:
  694. // - pastDrop: transaction dropped retroactively from a past block
  695. // - freshDrop: transaction dropped exactly at the block where the reorg is detected
  696. var pastDrop, freshDrop *types.Transaction
  697. // Create three transactions that will be added in the forked chain:
  698. // - pastAdd: transaction added before the reorganization is detected
  699. // - freshAdd: transaction added at the exact block the reorg is detected
  700. // - futureAdd: transaction added after the reorg has already finished
  701. var pastAdd, freshAdd, futureAdd *types.Transaction
  702. chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {
  703. switch i {
  704. case 0:
  705. pastDrop, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil), signer, key2)
  706. gen.AddTx(pastDrop) // This transaction will be dropped in the fork from below the split point
  707. gen.AddTx(postponed) // This transaction will be postponed till block #3 in the fork
  708. case 2:
  709. freshDrop, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil), signer, key2)
  710. gen.AddTx(freshDrop) // This transaction will be dropped in the fork from exactly at the split point
  711. gen.AddTx(swapped) // This transaction will be swapped out at the exact height
  712. gen.OffsetTime(9) // Lower the block difficulty to simulate a weaker chain
  713. }
  714. })
  715. // Import the chain. This runs all block validation rules.
  716. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  717. if i, err := blockchain.InsertChain(chain); err != nil {
  718. t.Fatalf("failed to insert original chain[%d]: %v", i, err)
  719. }
  720. defer blockchain.Stop()
  721. // overwrite the old chain
  722. chain, _ = GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 5, func(i int, gen *BlockGen) {
  723. switch i {
  724. case 0:
  725. pastAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key3)
  726. gen.AddTx(pastAdd) // This transaction needs to be injected during reorg
  727. case 2:
  728. gen.AddTx(postponed) // This transaction was postponed from block #1 in the original chain
  729. gen.AddTx(swapped) // This transaction was swapped from the exact current spot in the original chain
  730. freshAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key3)
  731. gen.AddTx(freshAdd) // This transaction will be added exactly at reorg time
  732. case 3:
  733. futureAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key3)
  734. gen.AddTx(futureAdd) // This transaction will be added after a full reorg
  735. }
  736. })
  737. if _, err := blockchain.InsertChain(chain); err != nil {
  738. t.Fatalf("failed to insert forked chain: %v", err)
  739. }
  740. // removed tx
  741. for i, tx := range (types.Transactions{pastDrop, freshDrop}) {
  742. if txn, _, _, _ := rawdb.ReadTransaction(db, tx.Hash()); txn != nil {
  743. t.Errorf("drop %d: tx %v found while shouldn't have been", i, txn)
  744. }
  745. if rcpt, _, _, _ := rawdb.ReadReceipt(db, tx.Hash()); rcpt != nil {
  746. t.Errorf("drop %d: receipt %v found while shouldn't have been", i, rcpt)
  747. }
  748. }
  749. // added tx
  750. for i, tx := range (types.Transactions{pastAdd, freshAdd, futureAdd}) {
  751. if txn, _, _, _ := rawdb.ReadTransaction(db, tx.Hash()); txn == nil {
  752. t.Errorf("add %d: expected tx to be found", i)
  753. }
  754. if rcpt, _, _, _ := rawdb.ReadReceipt(db, tx.Hash()); rcpt == nil {
  755. t.Errorf("add %d: expected receipt to be found", i)
  756. }
  757. }
  758. // shared tx
  759. for i, tx := range (types.Transactions{postponed, swapped}) {
  760. if txn, _, _, _ := rawdb.ReadTransaction(db, tx.Hash()); txn == nil {
  761. t.Errorf("share %d: expected tx to be found", i)
  762. }
  763. if rcpt, _, _, _ := rawdb.ReadReceipt(db, tx.Hash()); rcpt == nil {
  764. t.Errorf("share %d: expected receipt to be found", i)
  765. }
  766. }
  767. }
  768. func TestLogReorgs(t *testing.T) {
  769. var (
  770. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  771. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  772. db = ethdb.NewMemDatabase()
  773. // this code generates a log
  774. code = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
  775. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}}}
  776. genesis = gspec.MustCommit(db)
  777. signer = types.NewEIP155Signer(gspec.Config.ChainId)
  778. )
  779. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  780. defer blockchain.Stop()
  781. rmLogsCh := make(chan RemovedLogsEvent)
  782. blockchain.SubscribeRemovedLogsEvent(rmLogsCh)
  783. chain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) {
  784. if i == 1 {
  785. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), code), signer, key1)
  786. if err != nil {
  787. t.Fatalf("failed to create tx: %v", err)
  788. }
  789. gen.AddTx(tx)
  790. }
  791. })
  792. if _, err := blockchain.InsertChain(chain); err != nil {
  793. t.Fatalf("failed to insert chain: %v", err)
  794. }
  795. chain, _ = GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {})
  796. if _, err := blockchain.InsertChain(chain); err != nil {
  797. t.Fatalf("failed to insert forked chain: %v", err)
  798. }
  799. timeout := time.NewTimer(1 * time.Second)
  800. select {
  801. case ev := <-rmLogsCh:
  802. if len(ev.Logs) == 0 {
  803. t.Error("expected logs")
  804. }
  805. case <-timeout.C:
  806. t.Fatal("Timeout. There is no RemovedLogsEvent has been sent.")
  807. }
  808. }
  809. func TestReorgSideEvent(t *testing.T) {
  810. var (
  811. db = ethdb.NewMemDatabase()
  812. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  813. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  814. gspec = &Genesis{
  815. Config: params.TestChainConfig,
  816. Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}},
  817. }
  818. genesis = gspec.MustCommit(db)
  819. signer = types.NewEIP155Signer(gspec.Config.ChainId)
  820. )
  821. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  822. defer blockchain.Stop()
  823. chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {})
  824. if _, err := blockchain.InsertChain(chain); err != nil {
  825. t.Fatalf("failed to insert chain: %v", err)
  826. }
  827. replacementBlocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 4, func(i int, gen *BlockGen) {
  828. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), nil), signer, key1)
  829. if i == 2 {
  830. gen.OffsetTime(-9)
  831. }
  832. if err != nil {
  833. t.Fatalf("failed to create tx: %v", err)
  834. }
  835. gen.AddTx(tx)
  836. })
  837. chainSideCh := make(chan ChainSideEvent, 64)
  838. blockchain.SubscribeChainSideEvent(chainSideCh)
  839. if _, err := blockchain.InsertChain(replacementBlocks); err != nil {
  840. t.Fatalf("failed to insert chain: %v", err)
  841. }
  842. // first two block of the secondary chain are for a brief moment considered
  843. // side chains because up to that point the first one is considered the
  844. // heavier chain.
  845. expectedSideHashes := map[common.Hash]bool{
  846. replacementBlocks[0].Hash(): true,
  847. replacementBlocks[1].Hash(): true,
  848. chain[0].Hash(): true,
  849. chain[1].Hash(): true,
  850. chain[2].Hash(): true,
  851. }
  852. i := 0
  853. const timeoutDura = 10 * time.Second
  854. timeout := time.NewTimer(timeoutDura)
  855. done:
  856. for {
  857. select {
  858. case ev := <-chainSideCh:
  859. block := ev.Block
  860. if _, ok := expectedSideHashes[block.Hash()]; !ok {
  861. t.Errorf("%d: didn't expect %x to be in side chain", i, block.Hash())
  862. }
  863. i++
  864. if i == len(expectedSideHashes) {
  865. timeout.Stop()
  866. break done
  867. }
  868. timeout.Reset(timeoutDura)
  869. case <-timeout.C:
  870. t.Fatal("Timeout. Possibly not all blocks were triggered for sideevent")
  871. }
  872. }
  873. // make sure no more events are fired
  874. select {
  875. case e := <-chainSideCh:
  876. t.Errorf("unexpected event fired: %v", e)
  877. case <-time.After(250 * time.Millisecond):
  878. }
  879. }
  880. // Tests if the canonical block can be fetched from the database during chain insertion.
  881. func TestCanonicalBlockRetrieval(t *testing.T) {
  882. _, blockchain, err := newCanonical(ethash.NewFaker(), 0, true)
  883. if err != nil {
  884. t.Fatalf("failed to create pristine chain: %v", err)
  885. }
  886. defer blockchain.Stop()
  887. chain, _ := GenerateChain(blockchain.chainConfig, blockchain.genesisBlock, ethash.NewFaker(), blockchain.db, 10, func(i int, gen *BlockGen) {})
  888. var pend sync.WaitGroup
  889. pend.Add(len(chain))
  890. for i := range chain {
  891. go func(block *types.Block) {
  892. defer pend.Done()
  893. // try to retrieve a block by its canonical hash and see if the block data can be retrieved.
  894. for {
  895. ch := rawdb.ReadCanonicalHash(blockchain.db, block.NumberU64())
  896. if ch == (common.Hash{}) {
  897. continue // busy wait for canonical hash to be written
  898. }
  899. if ch != block.Hash() {
  900. t.Fatalf("unknown canonical hash, want %s, got %s", block.Hash().Hex(), ch.Hex())
  901. }
  902. fb := rawdb.ReadBlock(blockchain.db, ch, block.NumberU64())
  903. if fb == nil {
  904. t.Fatalf("unable to retrieve block %d for canonical hash: %s", block.NumberU64(), ch.Hex())
  905. }
  906. if fb.Hash() != block.Hash() {
  907. t.Fatalf("invalid block hash for block %d, want %s, got %s", block.NumberU64(), block.Hash().Hex(), fb.Hash().Hex())
  908. }
  909. return
  910. }
  911. }(chain[i])
  912. if _, err := blockchain.InsertChain(types.Blocks{chain[i]}); err != nil {
  913. t.Fatalf("failed to insert block %d: %v", i, err)
  914. }
  915. }
  916. pend.Wait()
  917. }
  918. func TestEIP155Transition(t *testing.T) {
  919. // Configure and generate a sample block chain
  920. var (
  921. db = ethdb.NewMemDatabase()
  922. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  923. address = crypto.PubkeyToAddress(key.PublicKey)
  924. funds = big.NewInt(1000000000)
  925. deleteAddr = common.Address{1}
  926. gspec = &Genesis{
  927. Config: &params.ChainConfig{ChainId: big.NewInt(1), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)},
  928. Alloc: GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}},
  929. }
  930. genesis = gspec.MustCommit(db)
  931. )
  932. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  933. defer blockchain.Stop()
  934. blocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 4, func(i int, block *BlockGen) {
  935. var (
  936. tx *types.Transaction
  937. err error
  938. basicTx = func(signer types.Signer) (*types.Transaction, error) {
  939. return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(big.Int), 21000, new(big.Int), nil), signer, key)
  940. }
  941. )
  942. switch i {
  943. case 0:
  944. tx, err = basicTx(types.HomesteadSigner{})
  945. if err != nil {
  946. t.Fatal(err)
  947. }
  948. block.AddTx(tx)
  949. case 2:
  950. tx, err = basicTx(types.HomesteadSigner{})
  951. if err != nil {
  952. t.Fatal(err)
  953. }
  954. block.AddTx(tx)
  955. tx, err = basicTx(types.NewEIP155Signer(gspec.Config.ChainId))
  956. if err != nil {
  957. t.Fatal(err)
  958. }
  959. block.AddTx(tx)
  960. case 3:
  961. tx, err = basicTx(types.HomesteadSigner{})
  962. if err != nil {
  963. t.Fatal(err)
  964. }
  965. block.AddTx(tx)
  966. tx, err = basicTx(types.NewEIP155Signer(gspec.Config.ChainId))
  967. if err != nil {
  968. t.Fatal(err)
  969. }
  970. block.AddTx(tx)
  971. }
  972. })
  973. if _, err := blockchain.InsertChain(blocks); err != nil {
  974. t.Fatal(err)
  975. }
  976. block := blockchain.GetBlockByNumber(1)
  977. if block.Transactions()[0].Protected() {
  978. t.Error("Expected block[0].txs[0] to not be replay protected")
  979. }
  980. block = blockchain.GetBlockByNumber(3)
  981. if block.Transactions()[0].Protected() {
  982. t.Error("Expected block[3].txs[0] to not be replay protected")
  983. }
  984. if !block.Transactions()[1].Protected() {
  985. t.Error("Expected block[3].txs[1] to be replay protected")
  986. }
  987. if _, err := blockchain.InsertChain(blocks[4:]); err != nil {
  988. t.Fatal(err)
  989. }
  990. // generate an invalid chain id transaction
  991. config := &params.ChainConfig{ChainId: big.NewInt(2), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)}
  992. blocks, _ = GenerateChain(config, blocks[len(blocks)-1], ethash.NewFaker(), db, 4, func(i int, block *BlockGen) {
  993. var (
  994. tx *types.Transaction
  995. err error
  996. basicTx = func(signer types.Signer) (*types.Transaction, error) {
  997. return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(big.Int), 21000, new(big.Int), nil), signer, key)
  998. }
  999. )
  1000. switch i {
  1001. case 0:
  1002. tx, err = basicTx(types.NewEIP155Signer(big.NewInt(2)))
  1003. if err != nil {
  1004. t.Fatal(err)
  1005. }
  1006. block.AddTx(tx)
  1007. }
  1008. })
  1009. _, err := blockchain.InsertChain(blocks)
  1010. if err != types.ErrInvalidChainId {
  1011. t.Error("expected error:", types.ErrInvalidChainId)
  1012. }
  1013. }
  1014. func TestEIP161AccountRemoval(t *testing.T) {
  1015. // Configure and generate a sample block chain
  1016. var (
  1017. db = ethdb.NewMemDatabase()
  1018. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1019. address = crypto.PubkeyToAddress(key.PublicKey)
  1020. funds = big.NewInt(1000000000)
  1021. theAddr = common.Address{1}
  1022. gspec = &Genesis{
  1023. Config: &params.ChainConfig{
  1024. ChainId: big.NewInt(1),
  1025. HomesteadBlock: new(big.Int),
  1026. EIP155Block: new(big.Int),
  1027. EIP158Block: big.NewInt(2),
  1028. },
  1029. Alloc: GenesisAlloc{address: {Balance: funds}},
  1030. }
  1031. genesis = gspec.MustCommit(db)
  1032. )
  1033. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  1034. defer blockchain.Stop()
  1035. blocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, block *BlockGen) {
  1036. var (
  1037. tx *types.Transaction
  1038. err error
  1039. signer = types.NewEIP155Signer(gspec.Config.ChainId)
  1040. )
  1041. switch i {
  1042. case 0:
  1043. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1044. case 1:
  1045. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1046. case 2:
  1047. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1048. }
  1049. if err != nil {
  1050. t.Fatal(err)
  1051. }
  1052. block.AddTx(tx)
  1053. })
  1054. // account must exist pre eip 161
  1055. if _, err := blockchain.InsertChain(types.Blocks{blocks[0]}); err != nil {
  1056. t.Fatal(err)
  1057. }
  1058. if st, _ := blockchain.State(); !st.Exist(theAddr) {
  1059. t.Error("expected account to exist")
  1060. }
  1061. // account needs to be deleted post eip 161
  1062. if _, err := blockchain.InsertChain(types.Blocks{blocks[1]}); err != nil {
  1063. t.Fatal(err)
  1064. }
  1065. if st, _ := blockchain.State(); st.Exist(theAddr) {
  1066. t.Error("account should not exist")
  1067. }
  1068. // account musn't be created post eip 161
  1069. if _, err := blockchain.InsertChain(types.Blocks{blocks[2]}); err != nil {
  1070. t.Fatal(err)
  1071. }
  1072. if st, _ := blockchain.State(); st.Exist(theAddr) {
  1073. t.Error("account should not exist")
  1074. }
  1075. }
  1076. // This is a regression test (i.e. as weird as it is, don't delete it ever), which
  1077. // tests that under weird reorg conditions the blockchain and its internal header-
  1078. // chain return the same latest block/header.
  1079. //
  1080. // https://github.com/ethereum/go-ethereum/pull/15941
  1081. func TestBlockchainHeaderchainReorgConsistency(t *testing.T) {
  1082. // Generate a canonical chain to act as the main dataset
  1083. engine := ethash.NewFaker()
  1084. db := ethdb.NewMemDatabase()
  1085. genesis := new(Genesis).MustCommit(db)
  1086. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1087. // Generate a bunch of fork blocks, each side forking from the canonical chain
  1088. forks := make([]*types.Block, len(blocks))
  1089. for i := 0; i < len(forks); i++ {
  1090. parent := genesis
  1091. if i > 0 {
  1092. parent = blocks[i-1]
  1093. }
  1094. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1095. forks[i] = fork[0]
  1096. }
  1097. // Import the canonical and fork chain side by side, verifying the current block
  1098. // and current header consistency
  1099. diskdb := ethdb.NewMemDatabase()
  1100. new(Genesis).MustCommit(diskdb)
  1101. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{})
  1102. if err != nil {
  1103. t.Fatalf("failed to create tester chain: %v", err)
  1104. }
  1105. for i := 0; i < len(blocks); i++ {
  1106. if _, err := chain.InsertChain(blocks[i : i+1]); err != nil {
  1107. t.Fatalf("block %d: failed to insert into chain: %v", i, err)
  1108. }
  1109. if chain.CurrentBlock().Hash() != chain.CurrentHeader().Hash() {
  1110. t.Errorf("block %d: current block/header mismatch: block #%d [%x…], header #%d [%x…]", i, chain.CurrentBlock().Number(), chain.CurrentBlock().Hash().Bytes()[:4], chain.CurrentHeader().Number, chain.CurrentHeader().Hash().Bytes()[:4])
  1111. }
  1112. if _, err := chain.InsertChain(forks[i : i+1]); err != nil {
  1113. t.Fatalf(" fork %d: failed to insert into chain: %v", i, err)
  1114. }
  1115. if chain.CurrentBlock().Hash() != chain.CurrentHeader().Hash() {
  1116. t.Errorf(" fork %d: current block/header mismatch: block #%d [%x…], header #%d [%x…]", i, chain.CurrentBlock().Number(), chain.CurrentBlock().Hash().Bytes()[:4], chain.CurrentHeader().Number, chain.CurrentHeader().Hash().Bytes()[:4])
  1117. }
  1118. }
  1119. }
  1120. // Tests that importing small side forks doesn't leave junk in the trie database
  1121. // cache (which would eventually cause memory issues).
  1122. func TestTrieForkGC(t *testing.T) {
  1123. // Generate a canonical chain to act as the main dataset
  1124. engine := ethash.NewFaker()
  1125. db := ethdb.NewMemDatabase()
  1126. genesis := new(Genesis).MustCommit(db)
  1127. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2*triesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1128. // Generate a bunch of fork blocks, each side forking from the canonical chain
  1129. forks := make([]*types.Block, len(blocks))
  1130. for i := 0; i < len(forks); i++ {
  1131. parent := genesis
  1132. if i > 0 {
  1133. parent = blocks[i-1]
  1134. }
  1135. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1136. forks[i] = fork[0]
  1137. }
  1138. // Import the canonical and fork chain side by side, forcing the trie cache to cache both
  1139. diskdb := ethdb.NewMemDatabase()
  1140. new(Genesis).MustCommit(diskdb)
  1141. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{})
  1142. if err != nil {
  1143. t.Fatalf("failed to create tester chain: %v", err)
  1144. }
  1145. for i := 0; i < len(blocks); i++ {
  1146. if _, err := chain.InsertChain(blocks[i : i+1]); err != nil {
  1147. t.Fatalf("block %d: failed to insert into chain: %v", i, err)
  1148. }
  1149. if _, err := chain.InsertChain(forks[i : i+1]); err != nil {
  1150. t.Fatalf("fork %d: failed to insert into chain: %v", i, err)
  1151. }
  1152. }
  1153. // Dereference all the recent tries and ensure no past trie is left in
  1154. for i := 0; i < triesInMemory; i++ {
  1155. chain.stateCache.TrieDB().Dereference(blocks[len(blocks)-1-i].Root(), common.Hash{})
  1156. chain.stateCache.TrieDB().Dereference(forks[len(blocks)-1-i].Root(), common.Hash{})
  1157. }
  1158. if len(chain.stateCache.TrieDB().Nodes()) > 0 {
  1159. t.Fatalf("stale tries still alive after garbase collection")
  1160. }
  1161. }
  1162. // Tests that doing large reorgs works even if the state associated with the
  1163. // forking point is not available any more.
  1164. func TestLargeReorgTrieGC(t *testing.T) {
  1165. // Generate the original common chain segment and the two competing forks
  1166. engine := ethash.NewFaker()
  1167. db := ethdb.NewMemDatabase()
  1168. genesis := new(Genesis).MustCommit(db)
  1169. shared, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1170. original, _ := GenerateChain(params.TestChainConfig, shared[len(shared)-1], engine, db, 2*triesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1171. competitor, _ := GenerateChain(params.TestChainConfig, shared[len(shared)-1], engine, db, 2*triesInMemory+1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{3}) })
  1172. // Import the shared chain and the original canonical one
  1173. diskdb := ethdb.NewMemDatabase()
  1174. new(Genesis).MustCommit(diskdb)
  1175. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{})
  1176. if err != nil {
  1177. t.Fatalf("failed to create tester chain: %v", err)
  1178. }
  1179. if _, err := chain.InsertChain(shared); err != nil {
  1180. t.Fatalf("failed to insert shared chain: %v", err)
  1181. }
  1182. if _, err := chain.InsertChain(original); err != nil {
  1183. t.Fatalf("failed to insert shared chain: %v", err)
  1184. }
  1185. // Ensure that the state associated with the forking point is pruned away
  1186. if node, _ := chain.stateCache.TrieDB().Node(shared[len(shared)-1].Root()); node != nil {
  1187. t.Fatalf("common-but-old ancestor still cache")
  1188. }
  1189. // Import the competitor chain without exceeding the canonical's TD and ensure
  1190. // we have not processed any of the blocks (protection against malicious blocks)
  1191. if _, err := chain.InsertChain(competitor[:len(competitor)-2]); err != nil {
  1192. t.Fatalf("failed to insert competitor chain: %v", err)
  1193. }
  1194. for i, block := range competitor[:len(competitor)-2] {
  1195. if node, _ := chain.stateCache.TrieDB().Node(block.Root()); node != nil {
  1196. t.Fatalf("competitor %d: low TD chain became processed", i)
  1197. }
  1198. }
  1199. // Import the head of the competitor chain, triggering the reorg and ensure we
  1200. // successfully reprocess all the stashed away blocks.
  1201. if _, err := chain.InsertChain(competitor[len(competitor)-2:]); err != nil {
  1202. t.Fatalf("failed to finalize competitor chain: %v", err)
  1203. }
  1204. for i, block := range competitor[:len(competitor)-triesInMemory] {
  1205. if node, _ := chain.stateCache.TrieDB().Node(block.Root()); node != nil {
  1206. t.Fatalf("competitor %d: competing chain state missing", i)
  1207. }
  1208. }
  1209. }
  1210. // Benchmarks large blocks with value transfers to non-existing accounts
  1211. func benchmarkLargeNumberOfValueToNonexisting(b *testing.B, numTxs, numBlocks int, recipientFn func(uint64) common.Address, dataFn func(uint64) []byte) {
  1212. var (
  1213. signer = types.HomesteadSigner{}
  1214. testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1215. testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
  1216. bankFunds = big.NewInt(100000000000000000)
  1217. gspec = Genesis{
  1218. Config: params.TestChainConfig,
  1219. Alloc: GenesisAlloc{
  1220. testBankAddress: {Balance: bankFunds},
  1221. common.HexToAddress("0xc0de"): {
  1222. Code: []byte{0x60, 0x01, 0x50},
  1223. Balance: big.NewInt(0),
  1224. }, // push 1, pop
  1225. },
  1226. GasLimit: 100e6, // 100 M
  1227. }
  1228. )
  1229. // Generate the original common chain segment and the two competing forks
  1230. engine := ethash.NewFaker()
  1231. db := ethdb.NewMemDatabase()
  1232. genesis := gspec.MustCommit(db)
  1233. blockGenerator := func(i int, block *BlockGen) {
  1234. block.SetCoinbase(common.Address{1})
  1235. for txi := 0; txi < numTxs; txi++ {
  1236. uniq := uint64(i*numTxs + txi)
  1237. recipient := recipientFn(uniq)
  1238. //recipient := common.BigToAddress(big.NewInt(0).SetUint64(1337 + uniq))
  1239. tx, err := types.SignTx(types.NewTransaction(uniq, recipient, big.NewInt(1), params.TxGas, big.NewInt(1), nil), signer, testBankKey)
  1240. if err != nil {
  1241. b.Error(err)
  1242. }
  1243. block.AddTx(tx)
  1244. }
  1245. }
  1246. shared, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, numBlocks, blockGenerator)
  1247. b.StopTimer()
  1248. b.ResetTimer()
  1249. for i := 0; i < b.N; i++ {
  1250. // Import the shared chain and the original canonical one
  1251. diskdb := ethdb.NewMemDatabase()
  1252. gspec.MustCommit(diskdb)
  1253. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{})
  1254. if err != nil {
  1255. b.Fatalf("failed to create tester chain: %v", err)
  1256. }
  1257. b.StartTimer()
  1258. if _, err := chain.InsertChain(shared); err != nil {
  1259. b.Fatalf("failed to insert shared chain: %v", err)
  1260. }
  1261. b.StopTimer()
  1262. if got := chain.CurrentBlock().Transactions().Len(); got != numTxs*numBlocks {
  1263. b.Fatalf("Transactions were not included, expected %d, got %d", (numTxs * numBlocks), got)
  1264. }
  1265. }
  1266. }
  1267. func BenchmarkBlockChain_1x1000ValueTransferToNonexisting(b *testing.B) {
  1268. var (
  1269. numTxs = 1000
  1270. numBlocks = 1
  1271. )
  1272. recipientFn := func(nonce uint64) common.Address {
  1273. return common.BigToAddress(big.NewInt(0).SetUint64(1337 + nonce))
  1274. }
  1275. dataFn := func(nonce uint64) []byte {
  1276. return nil
  1277. }
  1278. benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn)
  1279. }
  1280. func BenchmarkBlockChain_1x1000ValueTransferToExisting(b *testing.B) {
  1281. var (
  1282. numTxs = 1000
  1283. numBlocks = 1
  1284. )
  1285. b.StopTimer()
  1286. b.ResetTimer()
  1287. recipientFn := func(nonce uint64) common.Address {
  1288. return common.BigToAddress(big.NewInt(0).SetUint64(1337))
  1289. }
  1290. dataFn := func(nonce uint64) []byte {
  1291. return nil
  1292. }
  1293. benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn)
  1294. }
  1295. func BenchmarkBlockChain_1x1000Executions(b *testing.B) {
  1296. var (
  1297. numTxs = 1000
  1298. numBlocks = 1
  1299. )
  1300. b.StopTimer()
  1301. b.ResetTimer()
  1302. recipientFn := func(nonce uint64) common.Address {
  1303. return common.BigToAddress(big.NewInt(0).SetUint64(0xc0de))
  1304. }
  1305. dataFn := func(nonce uint64) []byte {
  1306. return nil
  1307. }
  1308. benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn)
  1309. }