blockchain_test.go 60 KB

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