blockchain_test.go 83 KB

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