blockchain_test.go 75 KB

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