blockchain_test.go 66 KB

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