blockchain_test.go 55 KB

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