blockchain_test.go 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220
  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. "errors"
  19. "fmt"
  20. "io/ioutil"
  21. "math/big"
  22. "math/rand"
  23. "os"
  24. "sync"
  25. "testing"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/consensus"
  29. "github.com/ethereum/go-ethereum/consensus/ethash"
  30. "github.com/ethereum/go-ethereum/core/rawdb"
  31. "github.com/ethereum/go-ethereum/core/state"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/core/vm"
  34. "github.com/ethereum/go-ethereum/crypto"
  35. "github.com/ethereum/go-ethereum/ethdb"
  36. "github.com/ethereum/go-ethereum/params"
  37. "github.com/ethereum/go-ethereum/trie"
  38. )
  39. // So we can deterministically seed different blockchains
  40. var (
  41. canonicalSeed = 1
  42. forkSeed1 = 2
  43. forkSeed2 = 3
  44. TestTriesInMemory = 128
  45. )
  46. // newCanonical creates a chain database, and injects a deterministic canonical
  47. // chain. Depending on the full flag, if creates either a full block chain or a
  48. // header only chain.
  49. func newCanonical(engine consensus.Engine, n int, full, pipeline bool) (ethdb.Database, *BlockChain, error) {
  50. var (
  51. db = rawdb.NewMemoryDatabase()
  52. genesis = new(Genesis).MustCommit(db)
  53. )
  54. // Initialize a fresh chain with only a genesis block
  55. var ops []BlockChainOption
  56. if pipeline {
  57. ops = append(ops, EnablePipelineCommit)
  58. }
  59. blockchain, _ := NewBlockChain(db, nil, params.AllEthashProtocolChanges, engine, vm.Config{}, nil, nil, ops...)
  60. // Create and inject the requested chain
  61. if n == 0 {
  62. return db, blockchain, nil
  63. }
  64. if full {
  65. // Full block-chain requested
  66. blocks := makeBlockChain(genesis, n, engine, db, canonicalSeed)
  67. _, err := blockchain.InsertChain(blocks)
  68. return db, blockchain, err
  69. }
  70. // Header-only chain requested
  71. headers := makeHeaderChain(genesis.Header(), n, engine, db, canonicalSeed)
  72. _, err := blockchain.InsertHeaderChain(headers, 1)
  73. return db, blockchain, err
  74. }
  75. // Test fork of length N starting from block i
  76. func testInvalidStateRootBlockImport(t *testing.T, blockchain *BlockChain, i, n int, pipeline bool) {
  77. // Copy old chain up to #i into a new db
  78. db, blockchain2, err := newCanonical(ethash.NewFaker(), i, true, pipeline)
  79. if err != nil {
  80. t.Fatal("could not make new canonical in testFork", err)
  81. }
  82. defer blockchain2.Stop()
  83. // Assert the chains have the same header/block at #i
  84. hash1 := blockchain.GetBlockByNumber(uint64(i)).Hash()
  85. hash2 := blockchain2.GetBlockByNumber(uint64(i)).Hash()
  86. if hash1 != hash2 {
  87. t.Errorf("chain content mismatch at %d: have hash %v, want hash %v", i, hash2, hash1)
  88. }
  89. // Extend the newly created chain
  90. blockChainB := makeBlockChain(blockchain2.CurrentBlock(), n, ethash.NewFaker(), db, forkSeed1)
  91. for idx, block := range blockChainB {
  92. block.SetRoot(common.Hash{0: byte(forkSeed1), 19: byte(idx)})
  93. }
  94. previousBlock := blockchain.CurrentBlock()
  95. // Sanity check that the forked chain can be imported into the original
  96. if _, err := blockchain.InsertChain(blockChainB); err == nil {
  97. t.Fatalf("failed to report insert error")
  98. }
  99. time.Sleep(2 * rewindBadBlockInterval)
  100. latestBlock := blockchain.CurrentBlock()
  101. if latestBlock.Hash() != previousBlock.Hash() || latestBlock.NumberU64() != previousBlock.NumberU64() {
  102. t.Fatalf("rewind do not take effect")
  103. }
  104. db, blockchain3, err := newCanonical(ethash.NewFaker(), i, true, pipeline)
  105. if err != nil {
  106. t.Fatal("could not make new canonical in testFork", err)
  107. }
  108. defer blockchain3.Stop()
  109. blockChainC := makeBlockChain(blockchain3.CurrentBlock(), n, ethash.NewFaker(), db, forkSeed2)
  110. if _, err := blockchain.InsertChain(blockChainC); err != nil {
  111. t.Fatalf("failed to insert forking chain: %v", err)
  112. }
  113. }
  114. // Test fork of length N starting from block i
  115. func testFork(t *testing.T, blockchain *BlockChain, i, n int, full, pipeline bool, comparator func(td1, td2 *big.Int)) {
  116. // Copy old chain up to #i into a new db
  117. db, blockchain2, err := newCanonical(ethash.NewFaker(), i, full, pipeline)
  118. if err != nil {
  119. t.Fatal("could not make new canonical in testFork", err)
  120. }
  121. defer blockchain2.Stop()
  122. // Assert the chains have the same header/block at #i
  123. var hash1, hash2 common.Hash
  124. if full {
  125. hash1 = blockchain.GetBlockByNumber(uint64(i)).Hash()
  126. hash2 = blockchain2.GetBlockByNumber(uint64(i)).Hash()
  127. } else {
  128. hash1 = blockchain.GetHeaderByNumber(uint64(i)).Hash()
  129. hash2 = blockchain2.GetHeaderByNumber(uint64(i)).Hash()
  130. }
  131. if hash1 != hash2 {
  132. t.Errorf("chain content mismatch at %d: have hash %v, want hash %v", i, hash2, hash1)
  133. }
  134. // Extend the newly created chain
  135. var (
  136. blockChainB []*types.Block
  137. headerChainB []*types.Header
  138. )
  139. if full {
  140. blockChainB = makeBlockChain(blockchain2.CurrentBlock(), n, ethash.NewFaker(), db, forkSeed1)
  141. if _, err := blockchain2.InsertChain(blockChainB); err != nil {
  142. t.Fatalf("failed to insert forking chain: %v", err)
  143. }
  144. } else {
  145. headerChainB = makeHeaderChain(blockchain2.CurrentHeader(), n, ethash.NewFaker(), db, forkSeed1)
  146. if _, err := blockchain2.InsertHeaderChain(headerChainB, 1); err != nil {
  147. t.Fatalf("failed to insert forking chain: %v", err)
  148. }
  149. }
  150. // Sanity check that the forked chain can be imported into the original
  151. var tdPre, tdPost *big.Int
  152. if full {
  153. tdPre = blockchain.GetTdByHash(blockchain.CurrentBlock().Hash())
  154. if err := testBlockChainImport(blockChainB, pipeline, blockchain); err != nil {
  155. t.Fatalf("failed to import forked block chain: %v", err)
  156. }
  157. tdPost = blockchain.GetTdByHash(blockChainB[len(blockChainB)-1].Hash())
  158. } else {
  159. tdPre = blockchain.GetTdByHash(blockchain.CurrentHeader().Hash())
  160. if err := testHeaderChainImport(headerChainB, blockchain); err != nil {
  161. t.Fatalf("failed to import forked header chain: %v", err)
  162. }
  163. tdPost = blockchain.GetTdByHash(headerChainB[len(headerChainB)-1].Hash())
  164. }
  165. // Compare the total difficulties of the chains
  166. comparator(tdPre, tdPost)
  167. }
  168. // testBlockChainImport tries to process a chain of blocks, writing them into
  169. // the database if successful.
  170. func testBlockChainImport(chain types.Blocks, pipelineCommit bool, blockchain *BlockChain) error {
  171. for _, block := range chain {
  172. // Try and process the block
  173. err := blockchain.engine.VerifyHeader(blockchain, block.Header(), true)
  174. if err == nil {
  175. err = blockchain.validator.ValidateBody(block)
  176. }
  177. if err != nil {
  178. if err == ErrKnownBlock {
  179. continue
  180. }
  181. return err
  182. }
  183. statedb, err := state.New(blockchain.GetBlockByHash(block.ParentHash()).Root(), blockchain.stateCache, nil)
  184. if err != nil {
  185. return err
  186. }
  187. statedb.SetExpectedStateRoot(block.Root())
  188. if pipelineCommit {
  189. statedb.EnablePipeCommit()
  190. }
  191. statedb, receipts, _, usedGas, err := blockchain.processor.Process(block, statedb, vm.Config{})
  192. if err != nil {
  193. blockchain.reportBlock(block, receipts, err)
  194. return err
  195. }
  196. err = blockchain.validator.ValidateState(block, statedb, receipts, usedGas, pipelineCommit)
  197. if err != nil {
  198. blockchain.reportBlock(block, receipts, err)
  199. return err
  200. }
  201. blockchain.chainmu.Lock()
  202. rawdb.WriteTd(blockchain.db, block.Hash(), block.NumberU64(), new(big.Int).Add(block.Difficulty(), blockchain.GetTdByHash(block.ParentHash())))
  203. rawdb.WriteBlock(blockchain.db, block)
  204. statedb.Finalise(false)
  205. statedb.AccountsIntermediateRoot()
  206. statedb.Commit(nil)
  207. blockchain.chainmu.Unlock()
  208. }
  209. return nil
  210. }
  211. // testHeaderChainImport tries to process a chain of header, writing them into
  212. // the database if successful.
  213. func testHeaderChainImport(chain []*types.Header, blockchain *BlockChain) error {
  214. for _, header := range chain {
  215. // Try and validate the header
  216. if err := blockchain.engine.VerifyHeader(blockchain, header, false); err != nil {
  217. return err
  218. }
  219. // Manually insert the header into the database, but don't reorganise (allows subsequent testing)
  220. blockchain.chainmu.Lock()
  221. rawdb.WriteTd(blockchain.db, header.Hash(), header.Number.Uint64(), new(big.Int).Add(header.Difficulty, blockchain.GetTdByHash(header.ParentHash)))
  222. rawdb.WriteHeader(blockchain.db, header)
  223. blockchain.chainmu.Unlock()
  224. }
  225. return nil
  226. }
  227. func TestBlockImportVerification(t *testing.T) {
  228. length := 5
  229. // Make first chain starting from genesis
  230. _, processor, err := newCanonical(ethash.NewFaker(), length, true, true)
  231. if err != nil {
  232. t.Fatalf("failed to make new canonical chain: %v", err)
  233. }
  234. defer processor.Stop()
  235. // Start fork from current height
  236. processor = EnablePipelineCommit(processor)
  237. testInvalidStateRootBlockImport(t, processor, length, 10, true)
  238. }
  239. func TestLastBlock(t *testing.T) {
  240. _, blockchain, err := newCanonical(ethash.NewFaker(), 0, true, false)
  241. if err != nil {
  242. t.Fatalf("failed to create pristine chain: %v", err)
  243. }
  244. defer blockchain.Stop()
  245. blocks := makeBlockChain(blockchain.CurrentBlock(), 1, ethash.NewFullFaker(), blockchain.db, 0)
  246. if _, err := blockchain.InsertChain(blocks); err != nil {
  247. t.Fatalf("Failed to insert block: %v", err)
  248. }
  249. if blocks[len(blocks)-1].Hash() != rawdb.ReadHeadBlockHash(blockchain.db) {
  250. t.Fatalf("Write/Get HeadBlockHash failed")
  251. }
  252. }
  253. // Tests that given a starting canonical chain of a given size, it can be extended
  254. // with various length chains.
  255. func TestExtendCanonicalHeaders(t *testing.T) {
  256. testExtendCanonical(t, false, false)
  257. }
  258. func TestExtendCanonicalBlocks(t *testing.T) {
  259. testExtendCanonical(t, true, false)
  260. testExtendCanonical(t, true, true)
  261. }
  262. func testExtendCanonical(t *testing.T, full, pipeline bool) {
  263. length := 5
  264. // Make first chain starting from genesis
  265. _, processor, err := newCanonical(ethash.NewFaker(), length, full, pipeline)
  266. if err != nil {
  267. t.Fatalf("failed to make new canonical chain: %v", err)
  268. }
  269. defer processor.Stop()
  270. // Define the difficulty comparator
  271. better := func(td1, td2 *big.Int) {
  272. if td2.Cmp(td1) <= 0 {
  273. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  274. }
  275. }
  276. // Start fork from current height
  277. testFork(t, processor, length, 1, full, pipeline, better)
  278. testFork(t, processor, length, 2, full, pipeline, better)
  279. testFork(t, processor, length, 5, full, pipeline, better)
  280. testFork(t, processor, length, 10, full, pipeline, better)
  281. }
  282. // Tests that given a starting canonical chain of a given size, creating shorter
  283. // forks do not take canonical ownership.
  284. func TestShorterForkHeaders(t *testing.T) { testShorterFork(t, false, false) }
  285. func TestShorterForkBlocks(t *testing.T) {
  286. testShorterFork(t, true, false)
  287. testShorterFork(t, true, true)
  288. }
  289. func testShorterFork(t *testing.T, full, pipeline bool) {
  290. length := 10
  291. // Make first chain starting from genesis
  292. _, processor, err := newCanonical(ethash.NewFaker(), length, full, pipeline)
  293. if err != nil {
  294. t.Fatalf("failed to make new canonical chain: %v", err)
  295. }
  296. defer processor.Stop()
  297. // Define the difficulty comparator
  298. worse := func(td1, td2 *big.Int) {
  299. if td2.Cmp(td1) >= 0 {
  300. t.Errorf("total difficulty mismatch: have %v, expected less than %v", td2, td1)
  301. }
  302. }
  303. // Sum of numbers must be less than `length` for this to be a shorter fork
  304. testFork(t, processor, 0, 3, full, pipeline, worse)
  305. testFork(t, processor, 0, 7, full, pipeline, worse)
  306. testFork(t, processor, 1, 1, full, pipeline, worse)
  307. testFork(t, processor, 1, 7, full, pipeline, worse)
  308. testFork(t, processor, 5, 3, full, pipeline, worse)
  309. testFork(t, processor, 5, 4, full, pipeline, worse)
  310. }
  311. // Tests that given a starting canonical chain of a given size, creating longer
  312. // forks do take canonical ownership.
  313. func TestLongerForkHeaders(t *testing.T) {
  314. testLongerFork(t, false, false)
  315. }
  316. func TestLongerForkBlocks(t *testing.T) {
  317. testLongerFork(t, true, false)
  318. testLongerFork(t, true, true)
  319. }
  320. func testLongerFork(t *testing.T, full, pipeline bool) {
  321. length := 10
  322. // Make first chain starting from genesis
  323. _, processor, err := newCanonical(ethash.NewFaker(), length, full, pipeline)
  324. if err != nil {
  325. t.Fatalf("failed to make new canonical chain: %v", err)
  326. }
  327. defer processor.Stop()
  328. // Define the difficulty comparator
  329. better := func(td1, td2 *big.Int) {
  330. if td2.Cmp(td1) <= 0 {
  331. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  332. }
  333. }
  334. // Sum of numbers must be greater than `length` for this to be a longer fork
  335. testFork(t, processor, 0, 11, full, pipeline, better)
  336. testFork(t, processor, 0, 15, full, pipeline, better)
  337. testFork(t, processor, 1, 10, full, pipeline, better)
  338. testFork(t, processor, 1, 12, full, pipeline, better)
  339. testFork(t, processor, 5, 6, full, pipeline, better)
  340. testFork(t, processor, 5, 8, full, pipeline, better)
  341. }
  342. // Tests that given a starting canonical chain of a given size, creating equal
  343. // forks do take canonical ownership.
  344. func TestEqualForkHeaders(t *testing.T) { testEqualFork(t, false, false) }
  345. func TestEqualForkBlocks(t *testing.T) {
  346. testEqualFork(t, true, true)
  347. testEqualFork(t, true, false)
  348. }
  349. func testEqualFork(t *testing.T, full, pipeline bool) {
  350. length := 10
  351. // Make first chain starting from genesis
  352. _, processor, err := newCanonical(ethash.NewFaker(), length, full, pipeline)
  353. if err != nil {
  354. t.Fatalf("failed to make new canonical chain: %v", err)
  355. }
  356. defer processor.Stop()
  357. // Define the difficulty comparator
  358. equal := func(td1, td2 *big.Int) {
  359. if td2.Cmp(td1) != 0 {
  360. t.Errorf("total difficulty mismatch: have %v, want %v", td2, td1)
  361. }
  362. }
  363. // Sum of numbers must be equal to `length` for this to be an equal fork
  364. testFork(t, processor, 0, 10, full, pipeline, equal)
  365. testFork(t, processor, 1, 9, full, pipeline, equal)
  366. testFork(t, processor, 2, 8, full, pipeline, equal)
  367. testFork(t, processor, 5, 5, full, pipeline, equal)
  368. testFork(t, processor, 6, 4, full, pipeline, equal)
  369. testFork(t, processor, 9, 1, full, pipeline, equal)
  370. }
  371. // Tests that chains missing links do not get accepted by the processor.
  372. func TestBrokenHeaderChain(t *testing.T) { testBrokenChain(t, false, false) }
  373. func TestBrokenBlockChain(t *testing.T) {
  374. testBrokenChain(t, true, false)
  375. testBrokenChain(t, true, true)
  376. }
  377. func testBrokenChain(t *testing.T, full, pipeline bool) {
  378. // Make chain starting from genesis
  379. db, blockchain, err := newCanonical(ethash.NewFaker(), 10, full, pipeline)
  380. if err != nil {
  381. t.Fatalf("failed to make new canonical chain: %v", err)
  382. }
  383. defer blockchain.Stop()
  384. // Create a forked chain, and try to insert with a missing link
  385. if full {
  386. chain := makeBlockChain(blockchain.CurrentBlock(), 5, ethash.NewFaker(), db, forkSeed1)[1:]
  387. if err := testBlockChainImport(chain, pipeline, blockchain); err == nil {
  388. t.Errorf("broken block chain not reported")
  389. }
  390. } else {
  391. chain := makeHeaderChain(blockchain.CurrentHeader(), 5, ethash.NewFaker(), db, forkSeed1)[1:]
  392. if err := testHeaderChainImport(chain, blockchain); err == nil {
  393. t.Errorf("broken header chain not reported")
  394. }
  395. }
  396. }
  397. // Tests that reorganising a long difficult chain after a short easy one
  398. // overwrites the canonical numbers and links in the database.
  399. func TestReorgLongHeaders(t *testing.T) { testReorgLong(t, false, false) }
  400. func TestReorgLongBlocks(t *testing.T) {
  401. testReorgLong(t, true, false)
  402. testReorgLong(t, true, true)
  403. }
  404. func testReorgLong(t *testing.T, full, pipeline bool) {
  405. testReorg(t, []int64{0, 0, -9}, []int64{0, 0, 0, -9}, 393280, full, pipeline)
  406. }
  407. // Tests that reorganising a short difficult chain after a long easy one
  408. // overwrites the canonical numbers and links in the database.
  409. func TestReorgShortHeaders(t *testing.T) { testReorgShort(t, false, false) }
  410. func TestReorgShortBlocks(t *testing.T) {
  411. testReorgShort(t, true, false)
  412. testReorgShort(t, true, true)
  413. }
  414. func testReorgShort(t *testing.T, full, pipeline bool) {
  415. // Create a long easy chain vs. a short heavy one. Due to difficulty adjustment
  416. // we need a fairly long chain of blocks with different difficulties for a short
  417. // one to become heavyer than a long one. The 96 is an empirical value.
  418. easy := make([]int64, 96)
  419. for i := 0; i < len(easy); i++ {
  420. easy[i] = 60
  421. }
  422. diff := make([]int64, len(easy)-1)
  423. for i := 0; i < len(diff); i++ {
  424. diff[i] = -9
  425. }
  426. testReorg(t, easy, diff, 12615120, full, pipeline)
  427. }
  428. func testReorg(t *testing.T, first, second []int64, td int64, full, pipeline bool) {
  429. // Create a pristine chain and database
  430. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full, pipeline)
  431. if err != nil {
  432. t.Fatalf("failed to create pristine chain: %v", err)
  433. }
  434. defer blockchain.Stop()
  435. // Insert an easy and a difficult chain afterwards
  436. easyBlocks, _ := GenerateChain(params.TestChainConfig, blockchain.CurrentBlock(), ethash.NewFaker(), db, len(first), func(i int, b *BlockGen) {
  437. b.OffsetTime(first[i])
  438. })
  439. diffBlocks, _ := GenerateChain(params.TestChainConfig, blockchain.CurrentBlock(), ethash.NewFaker(), db, len(second), func(i int, b *BlockGen) {
  440. b.OffsetTime(second[i])
  441. })
  442. if full {
  443. if _, err := blockchain.InsertChain(easyBlocks); err != nil {
  444. t.Fatalf("failed to insert easy chain: %v", err)
  445. }
  446. if _, err := blockchain.InsertChain(diffBlocks); err != nil {
  447. t.Fatalf("failed to insert difficult chain: %v", err)
  448. }
  449. } else {
  450. easyHeaders := make([]*types.Header, len(easyBlocks))
  451. for i, block := range easyBlocks {
  452. easyHeaders[i] = block.Header()
  453. }
  454. diffHeaders := make([]*types.Header, len(diffBlocks))
  455. for i, block := range diffBlocks {
  456. diffHeaders[i] = block.Header()
  457. }
  458. if _, err := blockchain.InsertHeaderChain(easyHeaders, 1); err != nil {
  459. t.Fatalf("failed to insert easy chain: %v", err)
  460. }
  461. if _, err := blockchain.InsertHeaderChain(diffHeaders, 1); err != nil {
  462. t.Fatalf("failed to insert difficult chain: %v", err)
  463. }
  464. }
  465. // Check that the chain is valid number and link wise
  466. if full {
  467. prev := blockchain.CurrentBlock()
  468. for block := blockchain.GetBlockByNumber(blockchain.CurrentBlock().NumberU64() - 1); block.NumberU64() != 0; prev, block = block, blockchain.GetBlockByNumber(block.NumberU64()-1) {
  469. if prev.ParentHash() != block.Hash() {
  470. t.Errorf("parent block hash mismatch: have %x, want %x", prev.ParentHash(), block.Hash())
  471. }
  472. }
  473. } else {
  474. prev := blockchain.CurrentHeader()
  475. for header := blockchain.GetHeaderByNumber(blockchain.CurrentHeader().Number.Uint64() - 1); header.Number.Uint64() != 0; prev, header = header, blockchain.GetHeaderByNumber(header.Number.Uint64()-1) {
  476. if prev.ParentHash != header.Hash() {
  477. t.Errorf("parent header hash mismatch: have %x, want %x", prev.ParentHash, header.Hash())
  478. }
  479. }
  480. }
  481. // Make sure the chain total difficulty is the correct one
  482. want := new(big.Int).Add(blockchain.genesisBlock.Difficulty(), big.NewInt(td))
  483. if full {
  484. if have := blockchain.GetTdByHash(blockchain.CurrentBlock().Hash()); have.Cmp(want) != 0 {
  485. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  486. }
  487. } else {
  488. if have := blockchain.GetTdByHash(blockchain.CurrentHeader().Hash()); have.Cmp(want) != 0 {
  489. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  490. }
  491. }
  492. }
  493. // Tests that the insertion functions detect banned hashes.
  494. func TestBadHeaderHashes(t *testing.T) { testBadHashes(t, false, false) }
  495. func TestBadBlockHashes(t *testing.T) {
  496. testBadHashes(t, true, true)
  497. testBadHashes(t, true, false)
  498. }
  499. func testBadHashes(t *testing.T, full, pipeline bool) {
  500. // Create a pristine chain and database
  501. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full, pipeline)
  502. if err != nil {
  503. t.Fatalf("failed to create pristine chain: %v", err)
  504. }
  505. defer blockchain.Stop()
  506. // Create a chain, ban a hash and try to import
  507. if full {
  508. blocks := makeBlockChain(blockchain.CurrentBlock(), 3, ethash.NewFaker(), db, 10)
  509. BadHashes[blocks[2].Header().Hash()] = true
  510. defer func() { delete(BadHashes, blocks[2].Header().Hash()) }()
  511. _, err = blockchain.InsertChain(blocks)
  512. } else {
  513. headers := makeHeaderChain(blockchain.CurrentHeader(), 3, ethash.NewFaker(), db, 10)
  514. BadHashes[headers[2].Hash()] = true
  515. defer func() { delete(BadHashes, headers[2].Hash()) }()
  516. _, err = blockchain.InsertHeaderChain(headers, 1)
  517. }
  518. if !errors.Is(err, ErrBlacklistedHash) {
  519. t.Errorf("error mismatch: have: %v, want: %v", err, ErrBlacklistedHash)
  520. }
  521. }
  522. // Tests that bad hashes are detected on boot, and the chain rolled back to a
  523. // good state prior to the bad hash.
  524. func TestReorgBadHeaderHashes(t *testing.T) { testReorgBadHashes(t, false, false) }
  525. func TestReorgBadBlockHashes(t *testing.T) {
  526. testReorgBadHashes(t, true, false)
  527. testReorgBadHashes(t, true, true)
  528. }
  529. func testReorgBadHashes(t *testing.T, full, pipeline bool) {
  530. // Create a pristine chain and database
  531. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full, pipeline)
  532. if err != nil {
  533. t.Fatalf("failed to create pristine chain: %v", err)
  534. }
  535. // Create a chain, import and ban afterwards
  536. headers := makeHeaderChain(blockchain.CurrentHeader(), 4, ethash.NewFaker(), db, 10)
  537. blocks := makeBlockChain(blockchain.CurrentBlock(), 4, ethash.NewFaker(), db, 10)
  538. if full {
  539. if _, err = blockchain.InsertChain(blocks); err != nil {
  540. t.Errorf("failed to import blocks: %v", err)
  541. }
  542. if blockchain.CurrentBlock().Hash() != blocks[3].Hash() {
  543. t.Errorf("last block hash mismatch: have: %x, want %x", blockchain.CurrentBlock().Hash(), blocks[3].Header().Hash())
  544. }
  545. BadHashes[blocks[3].Header().Hash()] = true
  546. defer func() { delete(BadHashes, blocks[3].Header().Hash()) }()
  547. } else {
  548. if _, err = blockchain.InsertHeaderChain(headers, 1); err != nil {
  549. t.Errorf("failed to import headers: %v", err)
  550. }
  551. if blockchain.CurrentHeader().Hash() != headers[3].Hash() {
  552. t.Errorf("last header hash mismatch: have: %x, want %x", blockchain.CurrentHeader().Hash(), headers[3].Hash())
  553. }
  554. BadHashes[headers[3].Hash()] = true
  555. defer func() { delete(BadHashes, headers[3].Hash()) }()
  556. }
  557. blockchain.Stop()
  558. // Create a new BlockChain and check that it rolled back the state.
  559. ncm, err := NewBlockChain(blockchain.db, nil, blockchain.chainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
  560. if err != nil {
  561. t.Fatalf("failed to create new chain manager: %v", err)
  562. }
  563. if full {
  564. if ncm.CurrentBlock().Hash() != blocks[2].Header().Hash() {
  565. t.Errorf("last block hash mismatch: have: %x, want %x", ncm.CurrentBlock().Hash(), blocks[2].Header().Hash())
  566. }
  567. if blocks[2].Header().GasLimit != ncm.GasLimit() {
  568. t.Errorf("last block gasLimit mismatch: have: %d, want %d", ncm.GasLimit(), blocks[2].Header().GasLimit)
  569. }
  570. } else {
  571. if ncm.CurrentHeader().Hash() != headers[2].Hash() {
  572. t.Errorf("last header hash mismatch: have: %x, want %x", ncm.CurrentHeader().Hash(), headers[2].Hash())
  573. }
  574. }
  575. ncm.Stop()
  576. }
  577. // Tests chain insertions in the face of one entity containing an invalid nonce.
  578. func TestHeadersInsertNonceError(t *testing.T) { testInsertNonceError(t, false, false) }
  579. func TestBlocksInsertNonceError(t *testing.T) {
  580. testInsertNonceError(t, true, false)
  581. testInsertNonceError(t, true, true)
  582. }
  583. func testInsertNonceError(t *testing.T, full, pipeline bool) {
  584. for i := 1; i < 25 && !t.Failed(); i++ {
  585. // Create a pristine chain and database
  586. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full, pipeline)
  587. if err != nil {
  588. t.Fatalf("failed to create pristine chain: %v", err)
  589. }
  590. defer blockchain.Stop()
  591. // Create and insert a chain with a failing nonce
  592. var (
  593. failAt int
  594. failRes int
  595. failNum uint64
  596. )
  597. if full {
  598. blocks := makeBlockChain(blockchain.CurrentBlock(), i, ethash.NewFaker(), db, 0)
  599. failAt = rand.Int() % len(blocks)
  600. failNum = blocks[failAt].NumberU64()
  601. blockchain.engine = ethash.NewFakeFailer(failNum)
  602. failRes, err = blockchain.InsertChain(blocks)
  603. } else {
  604. headers := makeHeaderChain(blockchain.CurrentHeader(), i, ethash.NewFaker(), db, 0)
  605. failAt = rand.Int() % len(headers)
  606. failNum = headers[failAt].Number.Uint64()
  607. blockchain.engine = ethash.NewFakeFailer(failNum)
  608. blockchain.hc.engine = blockchain.engine
  609. failRes, err = blockchain.InsertHeaderChain(headers, 1)
  610. }
  611. // Check that the returned error indicates the failure
  612. if failRes != failAt {
  613. t.Errorf("test %d: failure (%v) index mismatch: have %d, want %d", i, err, failRes, failAt)
  614. }
  615. // Check that all blocks after the failing block have been inserted
  616. for j := 0; j < i-failAt; j++ {
  617. if full {
  618. if block := blockchain.GetBlockByNumber(failNum + uint64(j)); block != nil {
  619. t.Errorf("test %d: invalid block in chain: %v", i, block)
  620. }
  621. } else {
  622. if header := blockchain.GetHeaderByNumber(failNum + uint64(j)); header != nil {
  623. t.Errorf("test %d: invalid header in chain: %v", i, header)
  624. }
  625. }
  626. }
  627. }
  628. }
  629. // Tests that fast importing a block chain produces the same chain data as the
  630. // classical full block processing.
  631. func TestFastVsFullChains(t *testing.T) {
  632. // Configure and generate a sample block chain
  633. var (
  634. gendb = rawdb.NewMemoryDatabase()
  635. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  636. address = crypto.PubkeyToAddress(key.PublicKey)
  637. funds = big.NewInt(1000000000)
  638. gspec = &Genesis{
  639. Config: params.TestChainConfig,
  640. Alloc: GenesisAlloc{address: {Balance: funds}},
  641. }
  642. genesis = gspec.MustCommit(gendb)
  643. signer = types.LatestSigner(gspec.Config)
  644. )
  645. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, 1024, func(i int, block *BlockGen) {
  646. block.SetCoinbase(common.Address{0x00})
  647. // If the block number is multiple of 3, send a few bonus transactions to the miner
  648. if i%3 == 2 {
  649. for j := 0; j < i%4+1; j++ {
  650. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, nil, nil), signer, key)
  651. if err != nil {
  652. panic(err)
  653. }
  654. block.AddTx(tx)
  655. }
  656. }
  657. // If the block number is a multiple of 5, add a few bonus uncles to the block
  658. if i%5 == 5 {
  659. block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
  660. }
  661. })
  662. // Import the chain as an archive node for the comparison baseline
  663. archiveDb := rawdb.NewMemoryDatabase()
  664. gspec.MustCommit(archiveDb)
  665. archive, _ := NewBlockChain(archiveDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  666. defer archive.Stop()
  667. if n, err := archive.InsertChain(blocks); err != nil {
  668. t.Fatalf("failed to process block %d: %v", n, err)
  669. }
  670. // Fast import the chain as a non-archive node to test
  671. fastDb := rawdb.NewMemoryDatabase()
  672. gspec.MustCommit(fastDb)
  673. fast, _ := NewBlockChain(fastDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  674. defer fast.Stop()
  675. headers := make([]*types.Header, len(blocks))
  676. for i, block := range blocks {
  677. headers[i] = block.Header()
  678. }
  679. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  680. t.Fatalf("failed to insert header %d: %v", n, err)
  681. }
  682. if n, err := fast.InsertReceiptChain(blocks, receipts, 0); err != nil {
  683. t.Fatalf("failed to insert receipt %d: %v", n, err)
  684. }
  685. // Freezer style fast import the chain.
  686. frdir, err := ioutil.TempDir("", "")
  687. if err != nil {
  688. t.Fatalf("failed to create temp freezer dir: %v", err)
  689. }
  690. defer os.Remove(frdir)
  691. ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false, false, false)
  692. if err != nil {
  693. t.Fatalf("failed to create temp freezer db: %v", err)
  694. }
  695. gspec.MustCommit(ancientDb)
  696. ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  697. defer ancient.Stop()
  698. if n, err := ancient.InsertHeaderChain(headers, 1); err != nil {
  699. t.Fatalf("failed to insert header %d: %v", n, err)
  700. }
  701. if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(len(blocks)/2)); err != nil {
  702. t.Fatalf("failed to insert receipt %d: %v", n, err)
  703. }
  704. // Iterate over all chain data components, and cross reference
  705. for i := 0; i < len(blocks); i++ {
  706. num, hash := blocks[i].NumberU64(), blocks[i].Hash()
  707. if ftd, atd := fast.GetTdByHash(hash), archive.GetTdByHash(hash); ftd.Cmp(atd) != 0 {
  708. t.Errorf("block #%d [%x]: td mismatch: fastdb %v, archivedb %v", num, hash, ftd, atd)
  709. }
  710. if antd, artd := ancient.GetTdByHash(hash), archive.GetTdByHash(hash); antd.Cmp(artd) != 0 {
  711. t.Errorf("block #%d [%x]: td mismatch: ancientdb %v, archivedb %v", num, hash, antd, artd)
  712. }
  713. if fheader, aheader := fast.GetHeaderByHash(hash), archive.GetHeaderByHash(hash); fheader.Hash() != aheader.Hash() {
  714. t.Errorf("block #%d [%x]: header mismatch: fastdb %v, archivedb %v", num, hash, fheader, aheader)
  715. }
  716. if anheader, arheader := ancient.GetHeaderByHash(hash), archive.GetHeaderByHash(hash); anheader.Hash() != arheader.Hash() {
  717. t.Errorf("block #%d [%x]: header mismatch: ancientdb %v, archivedb %v", num, hash, anheader, arheader)
  718. }
  719. if fblock, arblock, anblock := fast.GetBlockByHash(hash), archive.GetBlockByHash(hash), ancient.GetBlockByHash(hash); fblock.Hash() != arblock.Hash() || anblock.Hash() != arblock.Hash() {
  720. t.Errorf("block #%d [%x]: block mismatch: fastdb %v, ancientdb %v, archivedb %v", num, hash, fblock, anblock, arblock)
  721. } else if types.DeriveSha(fblock.Transactions(), trie.NewStackTrie(nil)) != types.DeriveSha(arblock.Transactions(), trie.NewStackTrie(nil)) || types.DeriveSha(anblock.Transactions(), trie.NewStackTrie(nil)) != types.DeriveSha(arblock.Transactions(), trie.NewStackTrie(nil)) {
  722. t.Errorf("block #%d [%x]: transactions mismatch: fastdb %v, ancientdb %v, archivedb %v", num, hash, fblock.Transactions(), anblock.Transactions(), arblock.Transactions())
  723. } else if types.CalcUncleHash(fblock.Uncles()) != types.CalcUncleHash(arblock.Uncles()) || types.CalcUncleHash(anblock.Uncles()) != types.CalcUncleHash(arblock.Uncles()) {
  724. t.Errorf("block #%d [%x]: uncles mismatch: fastdb %v, ancientdb %v, archivedb %v", num, hash, fblock.Uncles(), anblock, arblock.Uncles())
  725. }
  726. 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, trie.NewStackTrie(nil)) != types.DeriveSha(areceipts, trie.NewStackTrie(nil)) {
  727. t.Errorf("block #%d [%x]: receipts mismatch: fastdb %v, ancientdb %v, archivedb %v", num, hash, freceipts, anreceipts, areceipts)
  728. }
  729. }
  730. // Check that the canonical chains are the same between the databases
  731. for i := 0; i < len(blocks)+1; i++ {
  732. if fhash, ahash := rawdb.ReadCanonicalHash(fastDb, uint64(i)), rawdb.ReadCanonicalHash(archiveDb, uint64(i)); fhash != ahash {
  733. t.Errorf("block #%d: canonical hash mismatch: fastdb %v, archivedb %v", i, fhash, ahash)
  734. }
  735. if anhash, arhash := rawdb.ReadCanonicalHash(ancientDb, uint64(i)), rawdb.ReadCanonicalHash(archiveDb, uint64(i)); anhash != arhash {
  736. t.Errorf("block #%d: canonical hash mismatch: ancientdb %v, archivedb %v", i, anhash, arhash)
  737. }
  738. }
  739. }
  740. // Tests that various import methods move the chain head pointers to the correct
  741. // positions.
  742. func TestLightVsFastVsFullChainHeads(t *testing.T) {
  743. // Configure and generate a sample block chain
  744. var (
  745. gendb = rawdb.NewMemoryDatabase()
  746. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  747. address = crypto.PubkeyToAddress(key.PublicKey)
  748. funds = big.NewInt(1000000000)
  749. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{address: {Balance: funds}}}
  750. genesis = gspec.MustCommit(gendb)
  751. )
  752. height := uint64(1024)
  753. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil)
  754. // makeDb creates a db instance for testing.
  755. makeDb := func() (ethdb.Database, func()) {
  756. dir, err := ioutil.TempDir("", "")
  757. if err != nil {
  758. t.Fatalf("failed to create temp freezer dir: %v", err)
  759. }
  760. defer os.Remove(dir)
  761. db, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), dir, "", false, false, false)
  762. if err != nil {
  763. t.Fatalf("failed to create temp freezer db: %v", err)
  764. }
  765. gspec.MustCommit(db)
  766. return db, func() { os.RemoveAll(dir) }
  767. }
  768. // Configure a subchain to roll back
  769. remove := blocks[height/2].NumberU64()
  770. // Create a small assertion method to check the three heads
  771. assert := func(t *testing.T, kind string, chain *BlockChain, header uint64, fast uint64, block uint64) {
  772. t.Helper()
  773. if num := chain.CurrentBlock().NumberU64(); num != block {
  774. t.Errorf("%s head block mismatch: have #%v, want #%v", kind, num, block)
  775. }
  776. if num := chain.CurrentFastBlock().NumberU64(); num != fast {
  777. t.Errorf("%s head fast-block mismatch: have #%v, want #%v", kind, num, fast)
  778. }
  779. if num := chain.CurrentHeader().Number.Uint64(); num != header {
  780. t.Errorf("%s head header mismatch: have #%v, want #%v", kind, num, header)
  781. }
  782. }
  783. // Import the chain as an archive node and ensure all pointers are updated
  784. archiveDb, delfn := makeDb()
  785. defer delfn()
  786. archiveCaching := *defaultCacheConfig
  787. archiveCaching.TrieDirtyDisabled = true
  788. archive, _ := NewBlockChain(archiveDb, &archiveCaching, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  789. if n, err := archive.InsertChain(blocks); err != nil {
  790. t.Fatalf("failed to process block %d: %v", n, err)
  791. }
  792. defer archive.Stop()
  793. assert(t, "archive", archive, height, height, height)
  794. archive.SetHead(remove - 1)
  795. assert(t, "archive", archive, height/2, height/2, height/2)
  796. // Import the chain as a non-archive node and ensure all pointers are updated
  797. fastDb, delfn := makeDb()
  798. defer delfn()
  799. fast, _ := NewBlockChain(fastDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  800. defer fast.Stop()
  801. headers := make([]*types.Header, len(blocks))
  802. for i, block := range blocks {
  803. headers[i] = block.Header()
  804. }
  805. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  806. t.Fatalf("failed to insert header %d: %v", n, err)
  807. }
  808. if n, err := fast.InsertReceiptChain(blocks, receipts, 0); err != nil {
  809. t.Fatalf("failed to insert receipt %d: %v", n, err)
  810. }
  811. assert(t, "fast", fast, height, height, 0)
  812. fast.SetHead(remove - 1)
  813. assert(t, "fast", fast, height/2, height/2, 0)
  814. // Import the chain as a ancient-first node and ensure all pointers are updated
  815. ancientDb, delfn := makeDb()
  816. defer delfn()
  817. ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  818. defer ancient.Stop()
  819. if n, err := ancient.InsertHeaderChain(headers, 1); err != nil {
  820. t.Fatalf("failed to insert header %d: %v", n, err)
  821. }
  822. if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err != nil {
  823. t.Fatalf("failed to insert receipt %d: %v", n, err)
  824. }
  825. assert(t, "ancient", ancient, height, height, 0)
  826. ancient.SetHead(remove - 1)
  827. assert(t, "ancient", ancient, 0, 0, 0)
  828. if frozen, err := ancientDb.Ancients(); err != nil || frozen != 1 {
  829. t.Fatalf("failed to truncate ancient store, want %v, have %v", 1, frozen)
  830. }
  831. // Import the chain as a light node and ensure all pointers are updated
  832. lightDb, delfn := makeDb()
  833. defer delfn()
  834. light, _ := NewBlockChain(lightDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  835. if n, err := light.InsertHeaderChain(headers, 1); err != nil {
  836. t.Fatalf("failed to insert header %d: %v", n, err)
  837. }
  838. defer light.Stop()
  839. assert(t, "light", light, height, 0, 0)
  840. light.SetHead(remove - 1)
  841. assert(t, "light", light, height/2, 0, 0)
  842. }
  843. // Tests that chain reorganisations handle transaction removals and reinsertions.
  844. func TestChainTxReorgs(t *testing.T) {
  845. var (
  846. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  847. key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  848. key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  849. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  850. addr2 = crypto.PubkeyToAddress(key2.PublicKey)
  851. addr3 = crypto.PubkeyToAddress(key3.PublicKey)
  852. db = rawdb.NewMemoryDatabase()
  853. gspec = &Genesis{
  854. Config: params.TestChainConfig,
  855. GasLimit: 3141592,
  856. Alloc: GenesisAlloc{
  857. addr1: {Balance: big.NewInt(1000000)},
  858. addr2: {Balance: big.NewInt(1000000)},
  859. addr3: {Balance: big.NewInt(1000000)},
  860. },
  861. }
  862. genesis = gspec.MustCommit(db)
  863. signer = types.LatestSigner(gspec.Config)
  864. )
  865. // Create two transactions shared between the chains:
  866. // - postponed: transaction included at a later block in the forked chain
  867. // - swapped: transaction included at the same block number in the forked chain
  868. postponed, _ := types.SignTx(types.NewTransaction(0, addr1, big.NewInt(1000), params.TxGas, nil, nil), signer, key1)
  869. swapped, _ := types.SignTx(types.NewTransaction(1, addr1, big.NewInt(1000), params.TxGas, nil, nil), signer, key1)
  870. // Create two transactions that will be dropped by the forked chain:
  871. // - pastDrop: transaction dropped retroactively from a past block
  872. // - freshDrop: transaction dropped exactly at the block where the reorg is detected
  873. var pastDrop, freshDrop *types.Transaction
  874. // Create three transactions that will be added in the forked chain:
  875. // - pastAdd: transaction added before the reorganization is detected
  876. // - freshAdd: transaction added at the exact block the reorg is detected
  877. // - futureAdd: transaction added after the reorg has already finished
  878. var pastAdd, freshAdd, futureAdd *types.Transaction
  879. chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {
  880. switch i {
  881. case 0:
  882. pastDrop, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil), signer, key2)
  883. gen.AddTx(pastDrop) // This transaction will be dropped in the fork from below the split point
  884. gen.AddTx(postponed) // This transaction will be postponed till block #3 in the fork
  885. case 2:
  886. freshDrop, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil), signer, key2)
  887. gen.AddTx(freshDrop) // This transaction will be dropped in the fork from exactly at the split point
  888. gen.AddTx(swapped) // This transaction will be swapped out at the exact height
  889. gen.OffsetTime(9) // Lower the block difficulty to simulate a weaker chain
  890. }
  891. })
  892. // Import the chain. This runs all block validation rules.
  893. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  894. if i, err := blockchain.InsertChain(chain); err != nil {
  895. t.Fatalf("failed to insert original chain[%d]: %v", i, err)
  896. }
  897. defer blockchain.Stop()
  898. // overwrite the old chain
  899. chain, _ = GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 5, func(i int, gen *BlockGen) {
  900. switch i {
  901. case 0:
  902. pastAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key3)
  903. gen.AddTx(pastAdd) // This transaction needs to be injected during reorg
  904. case 2:
  905. gen.AddTx(postponed) // This transaction was postponed from block #1 in the original chain
  906. gen.AddTx(swapped) // This transaction was swapped from the exact current spot in the original chain
  907. freshAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key3)
  908. gen.AddTx(freshAdd) // This transaction will be added exactly at reorg time
  909. case 3:
  910. futureAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key3)
  911. gen.AddTx(futureAdd) // This transaction will be added after a full reorg
  912. }
  913. })
  914. if _, err := blockchain.InsertChain(chain); err != nil {
  915. t.Fatalf("failed to insert forked chain: %v", err)
  916. }
  917. // removed tx
  918. for i, tx := range (types.Transactions{pastDrop, freshDrop}) {
  919. if txn, _, _, _ := rawdb.ReadTransaction(db, tx.Hash()); txn != nil {
  920. t.Errorf("drop %d: tx %v found while shouldn't have been", i, txn)
  921. }
  922. if rcpt, _, _, _ := rawdb.ReadReceipt(db, tx.Hash(), blockchain.Config()); rcpt != nil {
  923. t.Errorf("drop %d: receipt %v found while shouldn't have been", i, rcpt)
  924. }
  925. }
  926. // added tx
  927. for i, tx := range (types.Transactions{pastAdd, freshAdd, futureAdd}) {
  928. if txn, _, _, _ := rawdb.ReadTransaction(db, tx.Hash()); txn == nil {
  929. t.Errorf("add %d: expected tx to be found", i)
  930. }
  931. if rcpt, _, _, _ := rawdb.ReadReceipt(db, tx.Hash(), blockchain.Config()); rcpt == nil {
  932. t.Errorf("add %d: expected receipt to be found", i)
  933. }
  934. }
  935. // shared tx
  936. for i, tx := range (types.Transactions{postponed, swapped}) {
  937. if txn, _, _, _ := rawdb.ReadTransaction(db, tx.Hash()); txn == nil {
  938. t.Errorf("share %d: expected tx to be found", i)
  939. }
  940. if rcpt, _, _, _ := rawdb.ReadReceipt(db, tx.Hash(), blockchain.Config()); rcpt == nil {
  941. t.Errorf("share %d: expected receipt to be found", i)
  942. }
  943. }
  944. }
  945. func TestLogReorgs(t *testing.T) {
  946. var (
  947. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  948. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  949. db = rawdb.NewMemoryDatabase()
  950. // this code generates a log
  951. code = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
  952. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}}}
  953. genesis = gspec.MustCommit(db)
  954. signer = types.LatestSigner(gspec.Config)
  955. )
  956. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  957. defer blockchain.Stop()
  958. rmLogsCh := make(chan RemovedLogsEvent)
  959. blockchain.SubscribeRemovedLogsEvent(rmLogsCh)
  960. chain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) {
  961. if i == 1 {
  962. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), code), signer, key1)
  963. if err != nil {
  964. t.Fatalf("failed to create tx: %v", err)
  965. }
  966. gen.AddTx(tx)
  967. }
  968. })
  969. if _, err := blockchain.InsertChain(chain); err != nil {
  970. t.Fatalf("failed to insert chain: %v", err)
  971. }
  972. chain, _ = GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {})
  973. done := make(chan struct{})
  974. go func() {
  975. ev := <-rmLogsCh
  976. if len(ev.Logs) == 0 {
  977. t.Error("expected logs")
  978. }
  979. close(done)
  980. }()
  981. if _, err := blockchain.InsertChain(chain); err != nil {
  982. t.Fatalf("failed to insert forked chain: %v", err)
  983. }
  984. timeout := time.NewTimer(1 * time.Second)
  985. defer timeout.Stop()
  986. select {
  987. case <-done:
  988. case <-timeout.C:
  989. t.Fatal("Timeout. There is no RemovedLogsEvent has been sent.")
  990. }
  991. }
  992. // This EVM code generates a log when the contract is created.
  993. var logCode = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
  994. // This test checks that log events and RemovedLogsEvent are sent
  995. // when the chain reorganizes.
  996. func TestLogRebirth(t *testing.T) {
  997. var (
  998. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  999. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  1000. db = rawdb.NewMemoryDatabase()
  1001. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}}}
  1002. genesis = gspec.MustCommit(db)
  1003. signer = types.LatestSigner(gspec.Config)
  1004. engine = ethash.NewFaker()
  1005. blockchain, _ = NewBlockChain(db, nil, gspec.Config, engine, vm.Config{}, nil, nil)
  1006. )
  1007. defer blockchain.Stop()
  1008. // The event channels.
  1009. newLogCh := make(chan []*types.Log, 10)
  1010. rmLogsCh := make(chan RemovedLogsEvent, 10)
  1011. blockchain.SubscribeLogsEvent(newLogCh)
  1012. blockchain.SubscribeRemovedLogsEvent(rmLogsCh)
  1013. // This chain contains a single log.
  1014. chain, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2, func(i int, gen *BlockGen) {
  1015. if i == 1 {
  1016. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), logCode), signer, key1)
  1017. if err != nil {
  1018. t.Fatalf("failed to create tx: %v", err)
  1019. }
  1020. gen.AddTx(tx)
  1021. }
  1022. })
  1023. if _, err := blockchain.InsertChain(chain); err != nil {
  1024. t.Fatalf("failed to insert chain: %v", err)
  1025. }
  1026. checkLogEvents(t, newLogCh, rmLogsCh, 1, 0)
  1027. // Generate long reorg chain containing another log. Inserting the
  1028. // chain removes one log and adds one.
  1029. forkChain, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2, func(i int, gen *BlockGen) {
  1030. if i == 1 {
  1031. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), logCode), signer, key1)
  1032. if err != nil {
  1033. t.Fatalf("failed to create tx: %v", err)
  1034. }
  1035. gen.AddTx(tx)
  1036. gen.OffsetTime(-9) // higher block difficulty
  1037. }
  1038. })
  1039. if _, err := blockchain.InsertChain(forkChain); err != nil {
  1040. t.Fatalf("failed to insert forked chain: %v", err)
  1041. }
  1042. checkLogEvents(t, newLogCh, rmLogsCh, 1, 1)
  1043. // This chain segment is rooted in the original chain, but doesn't contain any logs.
  1044. // When inserting it, the canonical chain switches away from forkChain and re-emits
  1045. // the log event for the old chain, as well as a RemovedLogsEvent for forkChain.
  1046. newBlocks, _ := GenerateChain(params.TestChainConfig, chain[len(chain)-1], engine, db, 1, func(i int, gen *BlockGen) {})
  1047. if _, err := blockchain.InsertChain(newBlocks); err != nil {
  1048. t.Fatalf("failed to insert forked chain: %v", err)
  1049. }
  1050. checkLogEvents(t, newLogCh, rmLogsCh, 1, 1)
  1051. }
  1052. // This test is a variation of TestLogRebirth. It verifies that log events are emitted
  1053. // when a side chain containing log events overtakes the canonical chain.
  1054. func TestSideLogRebirth(t *testing.T) {
  1055. var (
  1056. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1057. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  1058. db = rawdb.NewMemoryDatabase()
  1059. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}}}
  1060. genesis = gspec.MustCommit(db)
  1061. signer = types.LatestSigner(gspec.Config)
  1062. blockchain, _ = NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  1063. )
  1064. defer blockchain.Stop()
  1065. newLogCh := make(chan []*types.Log, 10)
  1066. rmLogsCh := make(chan RemovedLogsEvent, 10)
  1067. blockchain.SubscribeLogsEvent(newLogCh)
  1068. blockchain.SubscribeRemovedLogsEvent(rmLogsCh)
  1069. chain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) {
  1070. if i == 1 {
  1071. gen.OffsetTime(-9) // higher block difficulty
  1072. }
  1073. })
  1074. if _, err := blockchain.InsertChain(chain); err != nil {
  1075. t.Fatalf("failed to insert forked chain: %v", err)
  1076. }
  1077. checkLogEvents(t, newLogCh, rmLogsCh, 0, 0)
  1078. // Generate side chain with lower difficulty
  1079. sideChain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) {
  1080. if i == 1 {
  1081. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), logCode), signer, key1)
  1082. if err != nil {
  1083. t.Fatalf("failed to create tx: %v", err)
  1084. }
  1085. gen.AddTx(tx)
  1086. }
  1087. })
  1088. if _, err := blockchain.InsertChain(sideChain); err != nil {
  1089. t.Fatalf("failed to insert forked chain: %v", err)
  1090. }
  1091. checkLogEvents(t, newLogCh, rmLogsCh, 0, 0)
  1092. // Generate a new block based on side chain.
  1093. newBlocks, _ := GenerateChain(params.TestChainConfig, sideChain[len(sideChain)-1], ethash.NewFaker(), db, 1, func(i int, gen *BlockGen) {})
  1094. if _, err := blockchain.InsertChain(newBlocks); err != nil {
  1095. t.Fatalf("failed to insert forked chain: %v", err)
  1096. }
  1097. checkLogEvents(t, newLogCh, rmLogsCh, 1, 0)
  1098. }
  1099. func checkLogEvents(t *testing.T, logsCh <-chan []*types.Log, rmLogsCh <-chan RemovedLogsEvent, wantNew, wantRemoved int) {
  1100. t.Helper()
  1101. if len(logsCh) != wantNew {
  1102. t.Fatalf("wrong number of log events: got %d, want %d", len(logsCh), wantNew)
  1103. }
  1104. if len(rmLogsCh) != wantRemoved {
  1105. t.Fatalf("wrong number of removed log events: got %d, want %d", len(rmLogsCh), wantRemoved)
  1106. }
  1107. // Drain events.
  1108. for i := 0; i < len(logsCh); i++ {
  1109. <-logsCh
  1110. }
  1111. for i := 0; i < len(rmLogsCh); i++ {
  1112. <-rmLogsCh
  1113. }
  1114. }
  1115. func TestReorgSideEvent(t *testing.T) {
  1116. var (
  1117. db = rawdb.NewMemoryDatabase()
  1118. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1119. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  1120. gspec = &Genesis{
  1121. Config: params.TestChainConfig,
  1122. Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}},
  1123. }
  1124. genesis = gspec.MustCommit(db)
  1125. signer = types.LatestSigner(gspec.Config)
  1126. )
  1127. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  1128. defer blockchain.Stop()
  1129. chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {})
  1130. if _, err := blockchain.InsertChain(chain); err != nil {
  1131. t.Fatalf("failed to insert chain: %v", err)
  1132. }
  1133. replacementBlocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 4, func(i int, gen *BlockGen) {
  1134. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), nil), signer, key1)
  1135. if i == 2 {
  1136. gen.OffsetTime(-9)
  1137. }
  1138. if err != nil {
  1139. t.Fatalf("failed to create tx: %v", err)
  1140. }
  1141. gen.AddTx(tx)
  1142. })
  1143. chainSideCh := make(chan ChainSideEvent, 64)
  1144. blockchain.SubscribeChainSideEvent(chainSideCh)
  1145. if _, err := blockchain.InsertChain(replacementBlocks); err != nil {
  1146. t.Fatalf("failed to insert chain: %v", err)
  1147. }
  1148. // first two block of the secondary chain are for a brief moment considered
  1149. // side chains because up to that point the first one is considered the
  1150. // heavier chain.
  1151. expectedSideHashes := map[common.Hash]bool{
  1152. replacementBlocks[0].Hash(): true,
  1153. replacementBlocks[1].Hash(): true,
  1154. chain[0].Hash(): true,
  1155. chain[1].Hash(): true,
  1156. chain[2].Hash(): true,
  1157. }
  1158. i := 0
  1159. const timeoutDura = 10 * time.Second
  1160. timeout := time.NewTimer(timeoutDura)
  1161. done:
  1162. for {
  1163. select {
  1164. case ev := <-chainSideCh:
  1165. block := ev.Block
  1166. if _, ok := expectedSideHashes[block.Hash()]; !ok {
  1167. t.Errorf("%d: didn't expect %x to be in side chain", i, block.Hash())
  1168. }
  1169. i++
  1170. if i == len(expectedSideHashes) {
  1171. timeout.Stop()
  1172. break done
  1173. }
  1174. timeout.Reset(timeoutDura)
  1175. case <-timeout.C:
  1176. t.Fatal("Timeout. Possibly not all blocks were triggered for sideevent")
  1177. }
  1178. }
  1179. // make sure no more events are fired
  1180. select {
  1181. case e := <-chainSideCh:
  1182. t.Errorf("unexpected event fired: %v", e)
  1183. case <-time.After(250 * time.Millisecond):
  1184. }
  1185. }
  1186. // Tests if the canonical block can be fetched from the database during chain insertion.
  1187. func TestCanonicalBlockRetrieval(t *testing.T) {
  1188. _, blockchain, err := newCanonical(ethash.NewFaker(), 0, true, false)
  1189. if err != nil {
  1190. t.Fatalf("failed to create pristine chain: %v", err)
  1191. }
  1192. defer blockchain.Stop()
  1193. chain, _ := GenerateChain(blockchain.chainConfig, blockchain.genesisBlock, ethash.NewFaker(), blockchain.db, 10, func(i int, gen *BlockGen) {})
  1194. var pend sync.WaitGroup
  1195. pend.Add(len(chain))
  1196. for i := range chain {
  1197. go func(block *types.Block) {
  1198. defer pend.Done()
  1199. // try to retrieve a block by its canonical hash and see if the block data can be retrieved.
  1200. for {
  1201. ch := rawdb.ReadCanonicalHash(blockchain.db, block.NumberU64())
  1202. if ch == (common.Hash{}) {
  1203. continue // busy wait for canonical hash to be written
  1204. }
  1205. if ch != block.Hash() {
  1206. t.Errorf("unknown canonical hash, want %s, got %s", block.Hash().Hex(), ch.Hex())
  1207. return
  1208. }
  1209. fb := rawdb.ReadBlock(blockchain.db, ch, block.NumberU64())
  1210. if fb == nil {
  1211. t.Errorf("unable to retrieve block %d for canonical hash: %s", block.NumberU64(), ch.Hex())
  1212. return
  1213. }
  1214. if fb.Hash() != block.Hash() {
  1215. t.Errorf("invalid block hash for block %d, want %s, got %s", block.NumberU64(), block.Hash().Hex(), fb.Hash().Hex())
  1216. return
  1217. }
  1218. return
  1219. }
  1220. }(chain[i])
  1221. if _, err := blockchain.InsertChain(types.Blocks{chain[i]}); err != nil {
  1222. t.Fatalf("failed to insert block %d: %v", i, err)
  1223. }
  1224. }
  1225. pend.Wait()
  1226. }
  1227. func TestEIP155Transition(t *testing.T) {
  1228. // Configure and generate a sample block chain
  1229. var (
  1230. db = rawdb.NewMemoryDatabase()
  1231. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1232. address = crypto.PubkeyToAddress(key.PublicKey)
  1233. funds = big.NewInt(1000000000)
  1234. deleteAddr = common.Address{1}
  1235. gspec = &Genesis{
  1236. Config: &params.ChainConfig{ChainID: big.NewInt(1), EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)},
  1237. Alloc: GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}},
  1238. }
  1239. genesis = gspec.MustCommit(db)
  1240. )
  1241. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  1242. defer blockchain.Stop()
  1243. blocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 4, func(i int, block *BlockGen) {
  1244. var (
  1245. tx *types.Transaction
  1246. err error
  1247. basicTx = func(signer types.Signer) (*types.Transaction, error) {
  1248. return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1249. }
  1250. )
  1251. switch i {
  1252. case 0:
  1253. tx, err = basicTx(types.HomesteadSigner{})
  1254. if err != nil {
  1255. t.Fatal(err)
  1256. }
  1257. block.AddTx(tx)
  1258. case 2:
  1259. tx, err = basicTx(types.HomesteadSigner{})
  1260. if err != nil {
  1261. t.Fatal(err)
  1262. }
  1263. block.AddTx(tx)
  1264. tx, err = basicTx(types.LatestSigner(gspec.Config))
  1265. if err != nil {
  1266. t.Fatal(err)
  1267. }
  1268. block.AddTx(tx)
  1269. case 3:
  1270. tx, err = basicTx(types.HomesteadSigner{})
  1271. if err != nil {
  1272. t.Fatal(err)
  1273. }
  1274. block.AddTx(tx)
  1275. tx, err = basicTx(types.LatestSigner(gspec.Config))
  1276. if err != nil {
  1277. t.Fatal(err)
  1278. }
  1279. block.AddTx(tx)
  1280. }
  1281. })
  1282. if _, err := blockchain.InsertChain(blocks); err != nil {
  1283. t.Fatal(err)
  1284. }
  1285. block := blockchain.GetBlockByNumber(1)
  1286. if block.Transactions()[0].Protected() {
  1287. t.Error("Expected block[0].txs[0] to not be replay protected")
  1288. }
  1289. block = blockchain.GetBlockByNumber(3)
  1290. if block.Transactions()[0].Protected() {
  1291. t.Error("Expected block[3].txs[0] to not be replay protected")
  1292. }
  1293. if !block.Transactions()[1].Protected() {
  1294. t.Error("Expected block[3].txs[1] to be replay protected")
  1295. }
  1296. if _, err := blockchain.InsertChain(blocks[4:]); err != nil {
  1297. t.Fatal(err)
  1298. }
  1299. // generate an invalid chain id transaction
  1300. config := &params.ChainConfig{ChainID: big.NewInt(2), EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)}
  1301. blocks, _ = GenerateChain(config, blocks[len(blocks)-1], ethash.NewFaker(), db, 4, func(i int, block *BlockGen) {
  1302. var (
  1303. tx *types.Transaction
  1304. err error
  1305. basicTx = func(signer types.Signer) (*types.Transaction, error) {
  1306. return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1307. }
  1308. )
  1309. if i == 0 {
  1310. tx, err = basicTx(types.LatestSigner(config))
  1311. if err != nil {
  1312. t.Fatal(err)
  1313. }
  1314. block.AddTx(tx)
  1315. }
  1316. })
  1317. _, err := blockchain.InsertChain(blocks)
  1318. if err != types.ErrInvalidChainId {
  1319. t.Error("expected error:", types.ErrInvalidChainId)
  1320. }
  1321. }
  1322. func TestEIP161AccountRemoval(t *testing.T) {
  1323. // Configure and generate a sample block chain
  1324. var (
  1325. db = rawdb.NewMemoryDatabase()
  1326. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1327. address = crypto.PubkeyToAddress(key.PublicKey)
  1328. funds = big.NewInt(1000000000)
  1329. theAddr = common.Address{1}
  1330. gspec = &Genesis{
  1331. Config: &params.ChainConfig{
  1332. ChainID: big.NewInt(1),
  1333. HomesteadBlock: new(big.Int),
  1334. EIP155Block: new(big.Int),
  1335. EIP150Block: new(big.Int),
  1336. EIP158Block: big.NewInt(2),
  1337. },
  1338. Alloc: GenesisAlloc{address: {Balance: funds}},
  1339. }
  1340. genesis = gspec.MustCommit(db)
  1341. )
  1342. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  1343. defer blockchain.Stop()
  1344. blocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, block *BlockGen) {
  1345. var (
  1346. tx *types.Transaction
  1347. err error
  1348. signer = types.LatestSigner(gspec.Config)
  1349. )
  1350. switch i {
  1351. case 0:
  1352. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1353. case 1:
  1354. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1355. case 2:
  1356. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1357. }
  1358. if err != nil {
  1359. t.Fatal(err)
  1360. }
  1361. block.AddTx(tx)
  1362. })
  1363. // account must exist pre eip 161
  1364. if _, err := blockchain.InsertChain(types.Blocks{blocks[0]}); err != nil {
  1365. t.Fatal(err)
  1366. }
  1367. if st, _ := blockchain.State(); !st.Exist(theAddr) {
  1368. t.Error("expected account to exist")
  1369. }
  1370. // account needs to be deleted post eip 161
  1371. if _, err := blockchain.InsertChain(types.Blocks{blocks[1]}); err != nil {
  1372. t.Fatal(err)
  1373. }
  1374. if st, _ := blockchain.State(); st.Exist(theAddr) {
  1375. t.Error("account should not exist")
  1376. }
  1377. // account mustn't be created post eip 161
  1378. if _, err := blockchain.InsertChain(types.Blocks{blocks[2]}); err != nil {
  1379. t.Fatal(err)
  1380. }
  1381. if st, _ := blockchain.State(); st.Exist(theAddr) {
  1382. t.Error("account should not exist")
  1383. }
  1384. }
  1385. // This is a regression test (i.e. as weird as it is, don't delete it ever), which
  1386. // tests that under weird reorg conditions the blockchain and its internal header-
  1387. // chain return the same latest block/header.
  1388. //
  1389. // https://github.com/ethereum/go-ethereum/pull/15941
  1390. func TestBlockchainHeaderchainReorgConsistency(t *testing.T) {
  1391. // Generate a canonical chain to act as the main dataset
  1392. engine := ethash.NewFaker()
  1393. db := rawdb.NewMemoryDatabase()
  1394. genesis := new(Genesis).MustCommit(db)
  1395. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1396. // Generate a bunch of fork blocks, each side forking from the canonical chain
  1397. forks := make([]*types.Block, len(blocks))
  1398. for i := 0; i < len(forks); i++ {
  1399. parent := genesis
  1400. if i > 0 {
  1401. parent = blocks[i-1]
  1402. }
  1403. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1404. forks[i] = fork[0]
  1405. }
  1406. // Import the canonical and fork chain side by side, verifying the current block
  1407. // and current header consistency
  1408. diskdb := rawdb.NewMemoryDatabase()
  1409. new(Genesis).MustCommit(diskdb)
  1410. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
  1411. if err != nil {
  1412. t.Fatalf("failed to create tester chain: %v", err)
  1413. }
  1414. for i := 0; i < len(blocks); i++ {
  1415. if _, err := chain.InsertChain(blocks[i : i+1]); err != nil {
  1416. t.Fatalf("block %d: failed to insert into chain: %v", i, err)
  1417. }
  1418. if chain.CurrentBlock().Hash() != chain.CurrentHeader().Hash() {
  1419. 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])
  1420. }
  1421. if _, err := chain.InsertChain(forks[i : i+1]); err != nil {
  1422. t.Fatalf(" fork %d: failed to insert into chain: %v", i, err)
  1423. }
  1424. if chain.CurrentBlock().Hash() != chain.CurrentHeader().Hash() {
  1425. 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])
  1426. }
  1427. }
  1428. }
  1429. // Tests that importing small side forks doesn't leave junk in the trie database
  1430. // cache (which would eventually cause memory issues).
  1431. func TestTrieForkGC(t *testing.T) {
  1432. // Generate a canonical chain to act as the main dataset
  1433. engine := ethash.NewFaker()
  1434. db := rawdb.NewMemoryDatabase()
  1435. genesis := new(Genesis).MustCommit(db)
  1436. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2*TestTriesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1437. // Generate a bunch of fork blocks, each side forking from the canonical chain
  1438. forks := make([]*types.Block, len(blocks))
  1439. for i := 0; i < len(forks); i++ {
  1440. parent := genesis
  1441. if i > 0 {
  1442. parent = blocks[i-1]
  1443. }
  1444. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1445. forks[i] = fork[0]
  1446. }
  1447. // Import the canonical and fork chain side by side, forcing the trie cache to cache both
  1448. diskdb := rawdb.NewMemoryDatabase()
  1449. new(Genesis).MustCommit(diskdb)
  1450. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
  1451. if err != nil {
  1452. t.Fatalf("failed to create tester chain: %v", err)
  1453. }
  1454. for i := 0; i < len(blocks); i++ {
  1455. if _, err := chain.InsertChain(blocks[i : i+1]); err != nil {
  1456. t.Fatalf("block %d: failed to insert into chain: %v", i, err)
  1457. }
  1458. if _, err := chain.InsertChain(forks[i : i+1]); err != nil {
  1459. t.Fatalf("fork %d: failed to insert into chain: %v", i, err)
  1460. }
  1461. }
  1462. // Dereference all the recent tries and ensure no past trie is left in
  1463. for i := 0; i < TestTriesInMemory; i++ {
  1464. chain.stateCache.TrieDB().Dereference(blocks[len(blocks)-1-i].Root())
  1465. chain.stateCache.TrieDB().Dereference(forks[len(blocks)-1-i].Root())
  1466. }
  1467. if len(chain.stateCache.TrieDB().Nodes()) > 0 {
  1468. t.Fatalf("stale tries still alive after garbase collection")
  1469. }
  1470. }
  1471. // Tests that doing large reorgs works even if the state associated with the
  1472. // forking point is not available any more.
  1473. func TestLargeReorgTrieGC(t *testing.T) {
  1474. // Generate the original common chain segment and the two competing forks
  1475. engine := ethash.NewFaker()
  1476. db := rawdb.NewMemoryDatabase()
  1477. genesis := new(Genesis).MustCommit(db)
  1478. shared, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1479. original, _ := GenerateChain(params.TestChainConfig, shared[len(shared)-1], engine, db, 2*TestTriesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1480. competitor, _ := GenerateChain(params.TestChainConfig, shared[len(shared)-1], engine, db, 2*TestTriesInMemory+1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{3}) })
  1481. // Import the shared chain and the original canonical one
  1482. diskdb := rawdb.NewMemoryDatabase()
  1483. new(Genesis).MustCommit(diskdb)
  1484. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
  1485. if err != nil {
  1486. t.Fatalf("failed to create tester chain: %v", err)
  1487. }
  1488. if _, err := chain.InsertChain(shared); err != nil {
  1489. t.Fatalf("failed to insert shared chain: %v", err)
  1490. }
  1491. if _, err := chain.InsertChain(original); err != nil {
  1492. t.Fatalf("failed to insert original chain: %v", err)
  1493. }
  1494. // Ensure that the state associated with the forking point is pruned away
  1495. if node, _ := chain.stateCache.TrieDB().Node(shared[len(shared)-1].Root()); node != nil {
  1496. t.Fatalf("common-but-old ancestor still cache")
  1497. }
  1498. // Import the competitor chain without exceeding the canonical's TD and ensure
  1499. // we have not processed any of the blocks (protection against malicious blocks)
  1500. if _, err := chain.InsertChain(competitor[:len(competitor)-2]); err != nil {
  1501. t.Fatalf("failed to insert competitor chain: %v", err)
  1502. }
  1503. for i, block := range competitor[:len(competitor)-2] {
  1504. if node, _ := chain.stateCache.TrieDB().Node(block.Root()); node != nil {
  1505. t.Fatalf("competitor %d: low TD chain became processed", i)
  1506. }
  1507. }
  1508. // Import the head of the competitor chain, triggering the reorg and ensure we
  1509. // successfully reprocess all the stashed away blocks.
  1510. if _, err := chain.InsertChain(competitor[len(competitor)-2:]); err != nil {
  1511. t.Fatalf("failed to finalize competitor chain: %v", err)
  1512. }
  1513. for i, block := range competitor[:len(competitor)-TestTriesInMemory] {
  1514. if node, err := chain.stateCache.TrieDB().Node(block.Root()); node != nil {
  1515. t.Fatalf("competitor %d: competing chain state missing, err: %v", i, err)
  1516. }
  1517. }
  1518. }
  1519. func TestBlockchainRecovery(t *testing.T) {
  1520. // Configure and generate a sample block chain
  1521. var (
  1522. gendb = rawdb.NewMemoryDatabase()
  1523. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1524. address = crypto.PubkeyToAddress(key.PublicKey)
  1525. funds = big.NewInt(1000000000)
  1526. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{address: {Balance: funds}}}
  1527. genesis = gspec.MustCommit(gendb)
  1528. )
  1529. height := uint64(1024)
  1530. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil)
  1531. // Import the chain as a ancient-first node and ensure all pointers are updated
  1532. frdir, err := ioutil.TempDir("", "")
  1533. if err != nil {
  1534. t.Fatalf("failed to create temp freezer dir: %v", err)
  1535. }
  1536. defer os.Remove(frdir)
  1537. ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false, false, false)
  1538. if err != nil {
  1539. t.Fatalf("failed to create temp freezer db: %v", err)
  1540. }
  1541. gspec.MustCommit(ancientDb)
  1542. ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  1543. headers := make([]*types.Header, len(blocks))
  1544. for i, block := range blocks {
  1545. headers[i] = block.Header()
  1546. }
  1547. if n, err := ancient.InsertHeaderChain(headers, 1); err != nil {
  1548. t.Fatalf("failed to insert header %d: %v", n, err)
  1549. }
  1550. if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err != nil {
  1551. t.Fatalf("failed to insert receipt %d: %v", n, err)
  1552. }
  1553. rawdb.WriteLastPivotNumber(ancientDb, blocks[len(blocks)-1].NumberU64()) // Force fast sync behavior
  1554. ancient.Stop()
  1555. // Destroy head fast block manually
  1556. midBlock := blocks[len(blocks)/2]
  1557. rawdb.WriteHeadFastBlockHash(ancientDb, midBlock.Hash())
  1558. // Reopen broken blockchain again
  1559. ancient, _ = NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  1560. defer ancient.Stop()
  1561. if num := ancient.CurrentBlock().NumberU64(); num != 0 {
  1562. t.Errorf("head block mismatch: have #%v, want #%v", num, 0)
  1563. }
  1564. if num := ancient.CurrentFastBlock().NumberU64(); num != midBlock.NumberU64() {
  1565. t.Errorf("head fast-block mismatch: have #%v, want #%v", num, midBlock.NumberU64())
  1566. }
  1567. if num := ancient.CurrentHeader().Number.Uint64(); num != midBlock.NumberU64() {
  1568. t.Errorf("head header mismatch: have #%v, want #%v", num, midBlock.NumberU64())
  1569. }
  1570. }
  1571. func TestIncompleteAncientReceiptChainInsertion(t *testing.T) {
  1572. // Configure and generate a sample block chain
  1573. var (
  1574. gendb = rawdb.NewMemoryDatabase()
  1575. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1576. address = crypto.PubkeyToAddress(key.PublicKey)
  1577. funds = big.NewInt(1000000000)
  1578. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{address: {Balance: funds}}}
  1579. genesis = gspec.MustCommit(gendb)
  1580. )
  1581. height := uint64(1024)
  1582. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil)
  1583. // Import the chain as a ancient-first node and ensure all pointers are updated
  1584. frdir, err := ioutil.TempDir("", "")
  1585. if err != nil {
  1586. t.Fatalf("failed to create temp freezer dir: %v", err)
  1587. }
  1588. defer os.Remove(frdir)
  1589. ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false, false, false)
  1590. if err != nil {
  1591. t.Fatalf("failed to create temp freezer db: %v", err)
  1592. }
  1593. gspec.MustCommit(ancientDb)
  1594. ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
  1595. defer ancient.Stop()
  1596. headers := make([]*types.Header, len(blocks))
  1597. for i, block := range blocks {
  1598. headers[i] = block.Header()
  1599. }
  1600. if n, err := ancient.InsertHeaderChain(headers, 1); err != nil {
  1601. t.Fatalf("failed to insert header %d: %v", n, err)
  1602. }
  1603. // Abort ancient receipt chain insertion deliberately
  1604. ancient.terminateInsert = func(hash common.Hash, number uint64) bool {
  1605. return number == blocks[len(blocks)/2].NumberU64()
  1606. }
  1607. previousFastBlock := ancient.CurrentFastBlock()
  1608. if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err == nil {
  1609. t.Fatalf("failed to insert receipt %d: %v", n, err)
  1610. }
  1611. if ancient.CurrentFastBlock().NumberU64() != previousFastBlock.NumberU64() {
  1612. t.Fatalf("failed to rollback ancient data, want %d, have %d", previousFastBlock.NumberU64(), ancient.CurrentFastBlock().NumberU64())
  1613. }
  1614. if frozen, err := ancient.db.Ancients(); err != nil || frozen != 1 {
  1615. t.Fatalf("failed to truncate ancient data")
  1616. }
  1617. ancient.terminateInsert = nil
  1618. if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err != nil {
  1619. t.Fatalf("failed to insert receipt %d: %v", n, err)
  1620. }
  1621. if ancient.CurrentFastBlock().NumberU64() != blocks[len(blocks)-1].NumberU64() {
  1622. t.Fatalf("failed to insert ancient recept chain after rollback")
  1623. }
  1624. }
  1625. // Tests that importing a very large side fork, which is larger than the canon chain,
  1626. // but where the difficulty per block is kept low: this means that it will not
  1627. // overtake the 'canon' chain until after it's passed canon by about 200 blocks.
  1628. //
  1629. // Details at:
  1630. // - https://github.com/ethereum/go-ethereum/issues/18977
  1631. // - https://github.com/ethereum/go-ethereum/pull/18988
  1632. func TestLowDiffLongChain(t *testing.T) {
  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. // We must use a pretty long chain to ensure that the fork doesn't overtake us
  1638. // until after at least 128 blocks post tip
  1639. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 6*TestTriesInMemory, func(i int, b *BlockGen) {
  1640. b.SetCoinbase(common.Address{1})
  1641. b.OffsetTime(-9)
  1642. })
  1643. // Import the canonical chain
  1644. diskdb := rawdb.NewMemoryDatabase()
  1645. new(Genesis).MustCommit(diskdb)
  1646. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
  1647. if err != nil {
  1648. t.Fatalf("failed to create tester chain: %v", err)
  1649. }
  1650. if n, err := chain.InsertChain(blocks); err != nil {
  1651. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  1652. }
  1653. // Generate fork chain, starting from an early block
  1654. parent := blocks[10]
  1655. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 8*TestTriesInMemory, func(i int, b *BlockGen) {
  1656. b.SetCoinbase(common.Address{2})
  1657. })
  1658. // And now import the fork
  1659. if i, err := chain.InsertChain(fork); err != nil {
  1660. t.Fatalf("block %d: failed to insert into chain: %v", i, err)
  1661. }
  1662. head := chain.CurrentBlock()
  1663. if got := fork[len(fork)-1].Hash(); got != head.Hash() {
  1664. t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
  1665. }
  1666. // Sanity check that all the canonical numbers are present
  1667. header := chain.CurrentHeader()
  1668. for number := head.NumberU64(); number > 0; number-- {
  1669. if hash := chain.GetHeaderByNumber(number).Hash(); hash != header.Hash() {
  1670. t.Fatalf("header %d: canonical hash mismatch: have %x, want %x", number, hash, header.Hash())
  1671. }
  1672. header = chain.GetHeader(header.ParentHash, number-1)
  1673. }
  1674. }
  1675. // Tests that importing a sidechain (S), where
  1676. // - S is sidechain, containing blocks [Sn...Sm]
  1677. // - C is canon chain, containing blocks [G..Cn..Cm]
  1678. // - A common ancestor is placed at prune-point + blocksBetweenCommonAncestorAndPruneblock
  1679. // - The sidechain S is prepended with numCanonBlocksInSidechain blocks from the canon chain
  1680. func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommonAncestorAndPruneblock int) {
  1681. // Generate a canonical chain to act as the main dataset
  1682. engine := ethash.NewFaker()
  1683. db := rawdb.NewMemoryDatabase()
  1684. genesis := new(Genesis).MustCommit(db)
  1685. // Generate and import the canonical chain
  1686. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2*TestTriesInMemory, nil)
  1687. diskdb := rawdb.NewMemoryDatabase()
  1688. new(Genesis).MustCommit(diskdb)
  1689. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
  1690. if err != nil {
  1691. t.Fatalf("failed to create tester chain: %v", err)
  1692. }
  1693. if n, err := chain.InsertChain(blocks); err != nil {
  1694. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  1695. }
  1696. lastPrunedIndex := len(blocks) - TestTriesInMemory - 1
  1697. lastPrunedBlock := blocks[lastPrunedIndex-1]
  1698. firstNonPrunedBlock := blocks[len(blocks)-TestTriesInMemory]
  1699. // Verify pruning of lastPrunedBlock
  1700. if chain.HasBlockAndState(lastPrunedBlock.Hash(), lastPrunedBlock.NumberU64()) {
  1701. t.Errorf("Block %d not pruned", lastPrunedBlock.NumberU64())
  1702. }
  1703. // Verify firstNonPrunedBlock is not pruned
  1704. if !chain.HasBlockAndState(firstNonPrunedBlock.Hash(), firstNonPrunedBlock.NumberU64()) {
  1705. t.Errorf("Block %d pruned", firstNonPrunedBlock.NumberU64())
  1706. }
  1707. // Generate the sidechain
  1708. // First block should be a known block, block after should be a pruned block. So
  1709. // canon(pruned), side, side...
  1710. // Generate fork chain, make it longer than canon
  1711. parentIndex := lastPrunedIndex + blocksBetweenCommonAncestorAndPruneblock
  1712. parent := blocks[parentIndex]
  1713. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 2*TestTriesInMemory, func(i int, b *BlockGen) {
  1714. b.SetCoinbase(common.Address{2})
  1715. })
  1716. // Prepend the parent(s)
  1717. var sidechain []*types.Block
  1718. for i := numCanonBlocksInSidechain; i > 0; i-- {
  1719. sidechain = append(sidechain, blocks[parentIndex+1-i])
  1720. }
  1721. sidechain = append(sidechain, fork...)
  1722. _, err = chain.InsertChain(sidechain)
  1723. if err != nil {
  1724. t.Errorf("Got error, %v", err)
  1725. }
  1726. head := chain.CurrentBlock()
  1727. if got := fork[len(fork)-1].Hash(); got != head.Hash() {
  1728. t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
  1729. }
  1730. }
  1731. // Tests that importing a sidechain (S), where
  1732. // - S is sidechain, containing blocks [Sn...Sm]
  1733. // - C is canon chain, containing blocks [G..Cn..Cm]
  1734. // - The common ancestor Cc is pruned
  1735. // - The first block in S: Sn, is == Cn
  1736. // That is: the sidechain for import contains some blocks already present in canon chain.
  1737. // So the blocks are
  1738. // [ Cn, Cn+1, Cc, Sn+3 ... Sm]
  1739. // ^ ^ ^ pruned
  1740. func TestPrunedImportSide(t *testing.T) {
  1741. //glogger := log.NewGlogHandler(log.StreamHandler(os.Stdout, log.TerminalFormat(false)))
  1742. //glogger.Verbosity(3)
  1743. //log.Root().SetHandler(log.Handler(glogger))
  1744. testSideImport(t, 3, 3)
  1745. testSideImport(t, 3, -3)
  1746. testSideImport(t, 10, 0)
  1747. testSideImport(t, 1, 10)
  1748. testSideImport(t, 1, -10)
  1749. }
  1750. func TestInsertKnownHeaders(t *testing.T) { testInsertKnownChainData(t, "headers") }
  1751. func TestInsertKnownReceiptChain(t *testing.T) { testInsertKnownChainData(t, "receipts") }
  1752. func TestInsertKnownBlocks(t *testing.T) { testInsertKnownChainData(t, "blocks") }
  1753. func testInsertKnownChainData(t *testing.T, typ string) {
  1754. engine := ethash.NewFaker()
  1755. db := rawdb.NewMemoryDatabase()
  1756. genesis := new(Genesis).MustCommit(db)
  1757. blocks, receipts := GenerateChain(params.TestChainConfig, genesis, engine, db, 32, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1758. // A longer chain but total difficulty is lower.
  1759. blocks2, receipts2 := GenerateChain(params.TestChainConfig, blocks[len(blocks)-1], engine, db, 65, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1760. // A shorter chain but total difficulty is higher.
  1761. blocks3, receipts3 := GenerateChain(params.TestChainConfig, blocks[len(blocks)-1], engine, db, 64, func(i int, b *BlockGen) {
  1762. b.SetCoinbase(common.Address{1})
  1763. b.OffsetTime(-9) // A higher difficulty
  1764. })
  1765. // Import the shared chain and the original canonical one
  1766. dir, err := ioutil.TempDir("", "")
  1767. if err != nil {
  1768. t.Fatalf("failed to create temp freezer dir: %v", err)
  1769. }
  1770. defer os.Remove(dir)
  1771. chaindb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), dir, "", false, false, false)
  1772. if err != nil {
  1773. t.Fatalf("failed to create temp freezer db: %v", err)
  1774. }
  1775. new(Genesis).MustCommit(chaindb)
  1776. defer os.RemoveAll(dir)
  1777. chain, err := NewBlockChain(chaindb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
  1778. if err != nil {
  1779. t.Fatalf("failed to create tester chain: %v", err)
  1780. }
  1781. var (
  1782. inserter func(blocks []*types.Block, receipts []types.Receipts) error
  1783. asserter func(t *testing.T, block *types.Block)
  1784. )
  1785. if typ == "headers" {
  1786. inserter = func(blocks []*types.Block, receipts []types.Receipts) error {
  1787. headers := make([]*types.Header, 0, len(blocks))
  1788. for _, block := range blocks {
  1789. headers = append(headers, block.Header())
  1790. }
  1791. _, err := chain.InsertHeaderChain(headers, 1)
  1792. return err
  1793. }
  1794. asserter = func(t *testing.T, block *types.Block) {
  1795. if chain.CurrentHeader().Hash() != block.Hash() {
  1796. t.Fatalf("current head header mismatch, have %v, want %v", chain.CurrentHeader().Hash().Hex(), block.Hash().Hex())
  1797. }
  1798. }
  1799. } else if typ == "receipts" {
  1800. inserter = func(blocks []*types.Block, receipts []types.Receipts) error {
  1801. headers := make([]*types.Header, 0, len(blocks))
  1802. for _, block := range blocks {
  1803. headers = append(headers, block.Header())
  1804. }
  1805. _, err := chain.InsertHeaderChain(headers, 1)
  1806. if err != nil {
  1807. return err
  1808. }
  1809. _, err = chain.InsertReceiptChain(blocks, receipts, 0)
  1810. return err
  1811. }
  1812. asserter = func(t *testing.T, block *types.Block) {
  1813. if chain.CurrentFastBlock().Hash() != block.Hash() {
  1814. t.Fatalf("current head fast block mismatch, have %v, want %v", chain.CurrentFastBlock().Hash().Hex(), block.Hash().Hex())
  1815. }
  1816. }
  1817. } else {
  1818. inserter = func(blocks []*types.Block, receipts []types.Receipts) error {
  1819. _, err := chain.InsertChain(blocks)
  1820. return err
  1821. }
  1822. asserter = func(t *testing.T, block *types.Block) {
  1823. if chain.CurrentBlock().Hash() != block.Hash() {
  1824. t.Fatalf("current head block mismatch, have %v, want %v", chain.CurrentBlock().Hash().Hex(), block.Hash().Hex())
  1825. }
  1826. }
  1827. }
  1828. if err := inserter(blocks, receipts); err != nil {
  1829. t.Fatalf("failed to insert chain data: %v", err)
  1830. }
  1831. // Reimport the chain data again. All the imported
  1832. // chain data are regarded "known" data.
  1833. if err := inserter(blocks, receipts); err != nil {
  1834. t.Fatalf("failed to insert chain data: %v", err)
  1835. }
  1836. asserter(t, blocks[len(blocks)-1])
  1837. // Import a long canonical chain with some known data as prefix.
  1838. rollback := blocks[len(blocks)/2].NumberU64()
  1839. chain.SetHead(rollback - 1)
  1840. if err := inserter(append(blocks, blocks2...), append(receipts, receipts2...)); err != nil {
  1841. t.Fatalf("failed to insert chain data: %v", err)
  1842. }
  1843. asserter(t, blocks2[len(blocks2)-1])
  1844. // Import a heavier shorter but higher total difficulty chain with some known data as prefix.
  1845. if err := inserter(append(blocks, blocks3...), append(receipts, receipts3...)); err != nil {
  1846. t.Fatalf("failed to insert chain data: %v", err)
  1847. }
  1848. asserter(t, blocks3[len(blocks3)-1])
  1849. // Import a longer but lower total difficulty chain with some known data as prefix.
  1850. if err := inserter(append(blocks, blocks2...), append(receipts, receipts2...)); err != nil {
  1851. t.Fatalf("failed to insert chain data: %v", err)
  1852. }
  1853. // The head shouldn't change.
  1854. asserter(t, blocks3[len(blocks3)-1])
  1855. // Rollback the heavier chain and re-insert the longer chain again
  1856. chain.SetHead(rollback - 1)
  1857. if err := inserter(append(blocks, blocks2...), append(receipts, receipts2...)); err != nil {
  1858. t.Fatalf("failed to insert chain data: %v", err)
  1859. }
  1860. asserter(t, blocks2[len(blocks2)-1])
  1861. }
  1862. // getLongAndShortChains returns two chains,
  1863. // A is longer, B is heavier
  1864. func getLongAndShortChains() (*BlockChain, []*types.Block, []*types.Block, error) {
  1865. // Generate a canonical chain to act as the main dataset
  1866. engine := ethash.NewFaker()
  1867. db := rawdb.NewMemoryDatabase()
  1868. genesis := new(Genesis).MustCommit(db)
  1869. // Generate and import the canonical chain,
  1870. // Offset the time, to keep the difficulty low
  1871. longChain, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 80, func(i int, b *BlockGen) {
  1872. b.SetCoinbase(common.Address{1})
  1873. })
  1874. diskdb := rawdb.NewMemoryDatabase()
  1875. new(Genesis).MustCommit(diskdb)
  1876. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
  1877. if err != nil {
  1878. return nil, nil, nil, fmt.Errorf("failed to create tester chain: %v", err)
  1879. }
  1880. // Generate fork chain, make it shorter than canon, with common ancestor pretty early
  1881. parentIndex := 3
  1882. parent := longChain[parentIndex]
  1883. heavyChain, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 75, func(i int, b *BlockGen) {
  1884. b.SetCoinbase(common.Address{2})
  1885. b.OffsetTime(-9)
  1886. })
  1887. // Verify that the test is sane
  1888. var (
  1889. longerTd = new(big.Int)
  1890. shorterTd = new(big.Int)
  1891. )
  1892. for index, b := range longChain {
  1893. longerTd.Add(longerTd, b.Difficulty())
  1894. if index <= parentIndex {
  1895. shorterTd.Add(shorterTd, b.Difficulty())
  1896. }
  1897. }
  1898. for _, b := range heavyChain {
  1899. shorterTd.Add(shorterTd, b.Difficulty())
  1900. }
  1901. if shorterTd.Cmp(longerTd) <= 0 {
  1902. return nil, nil, nil, fmt.Errorf("Test is moot, heavyChain td (%v) must be larger than canon td (%v)", shorterTd, longerTd)
  1903. }
  1904. longerNum := longChain[len(longChain)-1].NumberU64()
  1905. shorterNum := heavyChain[len(heavyChain)-1].NumberU64()
  1906. if shorterNum >= longerNum {
  1907. return nil, nil, nil, fmt.Errorf("Test is moot, heavyChain num (%v) must be lower than canon num (%v)", shorterNum, longerNum)
  1908. }
  1909. return chain, longChain, heavyChain, nil
  1910. }
  1911. // TestReorgToShorterRemovesCanonMapping tests that if we
  1912. // 1. Have a chain [0 ... N .. X]
  1913. // 2. Reorg to shorter but heavier chain [0 ... N ... Y]
  1914. // 3. Then there should be no canon mapping for the block at height X
  1915. func TestReorgToShorterRemovesCanonMapping(t *testing.T) {
  1916. chain, canonblocks, sideblocks, err := getLongAndShortChains()
  1917. if err != nil {
  1918. t.Fatal(err)
  1919. }
  1920. if n, err := chain.InsertChain(canonblocks); err != nil {
  1921. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  1922. }
  1923. canonNum := chain.CurrentBlock().NumberU64()
  1924. _, err = chain.InsertChain(sideblocks)
  1925. if err != nil {
  1926. t.Errorf("Got error, %v", err)
  1927. }
  1928. head := chain.CurrentBlock()
  1929. if got := sideblocks[len(sideblocks)-1].Hash(); got != head.Hash() {
  1930. t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
  1931. }
  1932. // We have now inserted a sidechain.
  1933. if blockByNum := chain.GetBlockByNumber(canonNum); blockByNum != nil {
  1934. t.Errorf("expected block to be gone: %v", blockByNum.NumberU64())
  1935. }
  1936. if headerByNum := chain.GetHeaderByNumber(canonNum); headerByNum != nil {
  1937. t.Errorf("expected header to be gone: %v", headerByNum.Number.Uint64())
  1938. }
  1939. }
  1940. // TestReorgToShorterRemovesCanonMappingHeaderChain is the same scenario
  1941. // as TestReorgToShorterRemovesCanonMapping, but applied on headerchain
  1942. // imports -- that is, for fast sync
  1943. func TestReorgToShorterRemovesCanonMappingHeaderChain(t *testing.T) {
  1944. chain, canonblocks, sideblocks, err := getLongAndShortChains()
  1945. if err != nil {
  1946. t.Fatal(err)
  1947. }
  1948. // Convert into headers
  1949. canonHeaders := make([]*types.Header, len(canonblocks))
  1950. for i, block := range canonblocks {
  1951. canonHeaders[i] = block.Header()
  1952. }
  1953. if n, err := chain.InsertHeaderChain(canonHeaders, 0); err != nil {
  1954. t.Fatalf("header %d: failed to insert into chain: %v", n, err)
  1955. }
  1956. canonNum := chain.CurrentHeader().Number.Uint64()
  1957. sideHeaders := make([]*types.Header, len(sideblocks))
  1958. for i, block := range sideblocks {
  1959. sideHeaders[i] = block.Header()
  1960. }
  1961. if n, err := chain.InsertHeaderChain(sideHeaders, 0); err != nil {
  1962. t.Fatalf("header %d: failed to insert into chain: %v", n, err)
  1963. }
  1964. head := chain.CurrentHeader()
  1965. if got := sideblocks[len(sideblocks)-1].Hash(); got != head.Hash() {
  1966. t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
  1967. }
  1968. // We have now inserted a sidechain.
  1969. if blockByNum := chain.GetBlockByNumber(canonNum); blockByNum != nil {
  1970. t.Errorf("expected block to be gone: %v", blockByNum.NumberU64())
  1971. }
  1972. if headerByNum := chain.GetHeaderByNumber(canonNum); headerByNum != nil {
  1973. t.Errorf("expected header to be gone: %v", headerByNum.Number.Uint64())
  1974. }
  1975. }
  1976. func TestTransactionIndices(t *testing.T) {
  1977. // Configure and generate a sample block chain
  1978. var (
  1979. gendb = rawdb.NewMemoryDatabase()
  1980. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1981. address = crypto.PubkeyToAddress(key.PublicKey)
  1982. funds = big.NewInt(1000000000)
  1983. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{address: {Balance: funds}}}
  1984. genesis = gspec.MustCommit(gendb)
  1985. signer = types.LatestSigner(gspec.Config)
  1986. )
  1987. height := uint64(128)
  1988. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), func(i int, block *BlockGen) {
  1989. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, nil, nil), signer, key)
  1990. if err != nil {
  1991. panic(err)
  1992. }
  1993. block.AddTx(tx)
  1994. })
  1995. blocks2, _ := GenerateChain(gspec.Config, blocks[len(blocks)-1], ethash.NewFaker(), gendb, 10, nil)
  1996. check := func(tail *uint64, chain *BlockChain) {
  1997. stored := rawdb.ReadTxIndexTail(chain.db)
  1998. if tail == nil && stored != nil {
  1999. t.Fatalf("Oldest indexded block mismatch, want nil, have %d", *stored)
  2000. }
  2001. if tail != nil && *stored != *tail {
  2002. t.Fatalf("Oldest indexded block mismatch, want %d, have %d", *tail, *stored)
  2003. }
  2004. if tail != nil {
  2005. for i := *tail; i <= chain.CurrentBlock().NumberU64(); i++ {
  2006. block := rawdb.ReadBlock(chain.db, rawdb.ReadCanonicalHash(chain.db, i), i)
  2007. if block.Transactions().Len() == 0 {
  2008. continue
  2009. }
  2010. for _, tx := range block.Transactions() {
  2011. if index := rawdb.ReadTxLookupEntry(chain.db, tx.Hash()); index == nil {
  2012. t.Fatalf("Miss transaction indice, number %d hash %s", i, tx.Hash().Hex())
  2013. }
  2014. }
  2015. }
  2016. for i := uint64(0); i < *tail; i++ {
  2017. block := rawdb.ReadBlock(chain.db, rawdb.ReadCanonicalHash(chain.db, i), i)
  2018. if block.Transactions().Len() == 0 {
  2019. continue
  2020. }
  2021. for _, tx := range block.Transactions() {
  2022. if index := rawdb.ReadTxLookupEntry(chain.db, tx.Hash()); index != nil {
  2023. t.Fatalf("Transaction indice should be deleted, number %d hash %s", i, tx.Hash().Hex())
  2024. }
  2025. }
  2026. }
  2027. }
  2028. }
  2029. frdir, err := ioutil.TempDir("", "")
  2030. if err != nil {
  2031. t.Fatalf("failed to create temp freezer dir: %v", err)
  2032. }
  2033. defer os.Remove(frdir)
  2034. ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false, false, false)
  2035. if err != nil {
  2036. t.Fatalf("failed to create temp freezer db: %v", err)
  2037. }
  2038. gspec.MustCommit(ancientDb)
  2039. // Import all blocks into ancient db
  2040. l := uint64(0)
  2041. chain, err := NewBlockChain(ancientDb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, &l)
  2042. if err != nil {
  2043. t.Fatalf("failed to create tester chain: %v", err)
  2044. }
  2045. headers := make([]*types.Header, len(blocks))
  2046. for i, block := range blocks {
  2047. headers[i] = block.Header()
  2048. }
  2049. if n, err := chain.InsertHeaderChain(headers, 0); err != nil {
  2050. t.Fatalf("failed to insert header %d: %v", n, err)
  2051. }
  2052. if n, err := chain.InsertReceiptChain(blocks, receipts, 128); err != nil {
  2053. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2054. }
  2055. chain.Stop()
  2056. ancientDb.Close()
  2057. // Init block chain with external ancients, check all needed indices has been indexed.
  2058. limit := []uint64{0, 32, 64, 128}
  2059. for _, l := range limit {
  2060. ancientDb, err = rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false, false, false)
  2061. if err != nil {
  2062. t.Fatalf("failed to create temp freezer db: %v", err)
  2063. }
  2064. gspec.MustCommit(ancientDb)
  2065. chain, err = NewBlockChain(ancientDb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, &l)
  2066. if err != nil {
  2067. t.Fatalf("failed to create tester chain: %v", err)
  2068. }
  2069. time.Sleep(50 * time.Millisecond) // Wait for indices initialisation
  2070. var tail uint64
  2071. if l != 0 {
  2072. tail = uint64(128) - l + 1
  2073. }
  2074. check(&tail, chain)
  2075. chain.Stop()
  2076. ancientDb.Close()
  2077. }
  2078. // Reconstruct a block chain which only reserves HEAD-64 tx indices
  2079. ancientDb, err = rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false, false, false)
  2080. if err != nil {
  2081. t.Fatalf("failed to create temp freezer db: %v", err)
  2082. }
  2083. gspec.MustCommit(ancientDb)
  2084. limit = []uint64{0, 64 /* drop stale */, 32 /* shorten history */, 64 /* extend history */, 0 /* restore all */}
  2085. tails := []uint64{0, 67 /* 130 - 64 + 1 */, 100 /* 131 - 32 + 1 */, 69 /* 132 - 64 + 1 */, 0}
  2086. for i, l := range limit {
  2087. chain, err = NewBlockChain(ancientDb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, &l)
  2088. if err != nil {
  2089. t.Fatalf("failed to create tester chain: %v", err)
  2090. }
  2091. chain.InsertChain(blocks2[i : i+1]) // Feed chain a higher block to trigger indices updater.
  2092. time.Sleep(50 * time.Millisecond) // Wait for indices initialisation
  2093. check(&tails[i], chain)
  2094. chain.Stop()
  2095. }
  2096. }
  2097. func TestSkipStaleTxIndicesInFastSync(t *testing.T) {
  2098. // Configure and generate a sample block chain
  2099. var (
  2100. gendb = rawdb.NewMemoryDatabase()
  2101. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2102. address = crypto.PubkeyToAddress(key.PublicKey)
  2103. funds = big.NewInt(1000000000)
  2104. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{address: {Balance: funds}}}
  2105. genesis = gspec.MustCommit(gendb)
  2106. signer = types.LatestSigner(gspec.Config)
  2107. )
  2108. height := uint64(128)
  2109. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), func(i int, block *BlockGen) {
  2110. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, nil, nil), signer, key)
  2111. if err != nil {
  2112. panic(err)
  2113. }
  2114. block.AddTx(tx)
  2115. })
  2116. check := func(tail *uint64, chain *BlockChain) {
  2117. stored := rawdb.ReadTxIndexTail(chain.db)
  2118. if tail == nil && stored != nil {
  2119. t.Fatalf("Oldest indexded block mismatch, want nil, have %d", *stored)
  2120. }
  2121. if tail != nil && *stored != *tail {
  2122. t.Fatalf("Oldest indexded block mismatch, want %d, have %d", *tail, *stored)
  2123. }
  2124. if tail != nil {
  2125. for i := *tail; i <= chain.CurrentBlock().NumberU64(); i++ {
  2126. block := rawdb.ReadBlock(chain.db, rawdb.ReadCanonicalHash(chain.db, i), i)
  2127. if block.Transactions().Len() == 0 {
  2128. continue
  2129. }
  2130. for _, tx := range block.Transactions() {
  2131. if index := rawdb.ReadTxLookupEntry(chain.db, tx.Hash()); index == nil {
  2132. t.Fatalf("Miss transaction indice, number %d hash %s", i, tx.Hash().Hex())
  2133. }
  2134. }
  2135. }
  2136. for i := uint64(0); i < *tail; i++ {
  2137. block := rawdb.ReadBlock(chain.db, rawdb.ReadCanonicalHash(chain.db, i), i)
  2138. if block.Transactions().Len() == 0 {
  2139. continue
  2140. }
  2141. for _, tx := range block.Transactions() {
  2142. if index := rawdb.ReadTxLookupEntry(chain.db, tx.Hash()); index != nil {
  2143. t.Fatalf("Transaction indice should be deleted, number %d hash %s", i, tx.Hash().Hex())
  2144. }
  2145. }
  2146. }
  2147. }
  2148. }
  2149. frdir, err := ioutil.TempDir("", "")
  2150. if err != nil {
  2151. t.Fatalf("failed to create temp freezer dir: %v", err)
  2152. }
  2153. defer os.Remove(frdir)
  2154. ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false, false, false)
  2155. if err != nil {
  2156. t.Fatalf("failed to create temp freezer db: %v", err)
  2157. }
  2158. gspec.MustCommit(ancientDb)
  2159. // Import all blocks into ancient db, only HEAD-32 indices are kept.
  2160. l := uint64(32)
  2161. chain, err := NewBlockChain(ancientDb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, &l)
  2162. if err != nil {
  2163. t.Fatalf("failed to create tester chain: %v", err)
  2164. }
  2165. headers := make([]*types.Header, len(blocks))
  2166. for i, block := range blocks {
  2167. headers[i] = block.Header()
  2168. }
  2169. if n, err := chain.InsertHeaderChain(headers, 0); err != nil {
  2170. t.Fatalf("failed to insert header %d: %v", n, err)
  2171. }
  2172. // The indices before ancient-N(32) should be ignored. After that all blocks should be indexed.
  2173. if n, err := chain.InsertReceiptChain(blocks, receipts, 64); err != nil {
  2174. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2175. }
  2176. tail := uint64(32)
  2177. check(&tail, chain)
  2178. }
  2179. // Benchmarks large blocks with value transfers to non-existing accounts
  2180. func benchmarkLargeNumberOfValueToNonexisting(b *testing.B, numTxs, numBlocks int, recipientFn func(uint64) common.Address, dataFn func(uint64) []byte) {
  2181. var (
  2182. signer = types.HomesteadSigner{}
  2183. testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2184. testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
  2185. bankFunds = big.NewInt(100000000000000000)
  2186. gspec = Genesis{
  2187. Config: params.TestChainConfig,
  2188. Alloc: GenesisAlloc{
  2189. testBankAddress: {Balance: bankFunds},
  2190. common.HexToAddress("0xc0de"): {
  2191. Code: []byte{0x60, 0x01, 0x50},
  2192. Balance: big.NewInt(0),
  2193. }, // push 1, pop
  2194. },
  2195. GasLimit: 100e6, // 100 M
  2196. }
  2197. )
  2198. // Generate the original common chain segment and the two competing forks
  2199. engine := ethash.NewFaker()
  2200. db := rawdb.NewMemoryDatabase()
  2201. genesis := gspec.MustCommit(db)
  2202. blockGenerator := func(i int, block *BlockGen) {
  2203. block.SetCoinbase(common.Address{1})
  2204. for txi := 0; txi < numTxs; txi++ {
  2205. uniq := uint64(i*numTxs + txi)
  2206. recipient := recipientFn(uniq)
  2207. tx, err := types.SignTx(types.NewTransaction(uniq, recipient, big.NewInt(1), params.TxGas, big.NewInt(1), nil), signer, testBankKey)
  2208. if err != nil {
  2209. b.Error(err)
  2210. }
  2211. block.AddTx(tx)
  2212. }
  2213. }
  2214. shared, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, numBlocks, blockGenerator)
  2215. b.StopTimer()
  2216. b.ResetTimer()
  2217. for i := 0; i < b.N; i++ {
  2218. // Import the shared chain and the original canonical one
  2219. diskdb := rawdb.NewMemoryDatabase()
  2220. gspec.MustCommit(diskdb)
  2221. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
  2222. if err != nil {
  2223. b.Fatalf("failed to create tester chain: %v", err)
  2224. }
  2225. b.StartTimer()
  2226. if _, err := chain.InsertChain(shared); err != nil {
  2227. b.Fatalf("failed to insert shared chain: %v", err)
  2228. }
  2229. b.StopTimer()
  2230. if got := chain.CurrentBlock().Transactions().Len(); got != numTxs*numBlocks {
  2231. b.Fatalf("Transactions were not included, expected %d, got %d", numTxs*numBlocks, got)
  2232. }
  2233. }
  2234. }
  2235. func BenchmarkBlockChain_1x1000ValueTransferToNonexisting(b *testing.B) {
  2236. var (
  2237. numTxs = 1000
  2238. numBlocks = 1
  2239. )
  2240. recipientFn := func(nonce uint64) common.Address {
  2241. return common.BigToAddress(big.NewInt(0).SetUint64(1337 + nonce))
  2242. }
  2243. dataFn := func(nonce uint64) []byte {
  2244. return nil
  2245. }
  2246. benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn)
  2247. }
  2248. func BenchmarkBlockChain_1x1000ValueTransferToExisting(b *testing.B) {
  2249. var (
  2250. numTxs = 1000
  2251. numBlocks = 1
  2252. )
  2253. b.StopTimer()
  2254. b.ResetTimer()
  2255. recipientFn := func(nonce uint64) common.Address {
  2256. return common.BigToAddress(big.NewInt(0).SetUint64(1337))
  2257. }
  2258. dataFn := func(nonce uint64) []byte {
  2259. return nil
  2260. }
  2261. benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn)
  2262. }
  2263. func BenchmarkBlockChain_1x1000Executions(b *testing.B) {
  2264. var (
  2265. numTxs = 1000
  2266. numBlocks = 1
  2267. )
  2268. b.StopTimer()
  2269. b.ResetTimer()
  2270. recipientFn := func(nonce uint64) common.Address {
  2271. return common.BigToAddress(big.NewInt(0).SetUint64(0xc0de))
  2272. }
  2273. dataFn := func(nonce uint64) []byte {
  2274. return nil
  2275. }
  2276. benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn)
  2277. }
  2278. // Tests that importing a some old blocks, where all blocks are before the
  2279. // pruning point.
  2280. // This internally leads to a sidechain import, since the blocks trigger an
  2281. // ErrPrunedAncestor error.
  2282. // This may e.g. happen if
  2283. // 1. Downloader rollbacks a batch of inserted blocks and exits
  2284. // 2. Downloader starts to sync again
  2285. // 3. The blocks fetched are all known and canonical blocks
  2286. func TestSideImportPrunedBlocks(t *testing.T) {
  2287. // Generate a canonical chain to act as the main dataset
  2288. engine := ethash.NewFaker()
  2289. db := rawdb.NewMemoryDatabase()
  2290. genesis := new(Genesis).MustCommit(db)
  2291. // Generate and import the canonical chain
  2292. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2*TestTriesInMemory, nil)
  2293. diskdb := rawdb.NewMemoryDatabase()
  2294. new(Genesis).MustCommit(diskdb)
  2295. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
  2296. if err != nil {
  2297. t.Fatalf("failed to create tester chain: %v", err)
  2298. }
  2299. if n, err := chain.InsertChain(blocks); err != nil {
  2300. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2301. }
  2302. lastPrunedIndex := len(blocks) - TestTriesInMemory - 1
  2303. lastPrunedBlock := blocks[lastPrunedIndex-1]
  2304. // Verify pruning of lastPrunedBlock
  2305. if chain.HasBlockAndState(lastPrunedBlock.Hash(), lastPrunedBlock.NumberU64()) {
  2306. t.Errorf("Block %d not pruned", lastPrunedBlock.NumberU64())
  2307. }
  2308. firstNonPrunedBlock := blocks[len(blocks)-TestTriesInMemory]
  2309. // Verify firstNonPrunedBlock is not pruned
  2310. if !chain.HasBlockAndState(firstNonPrunedBlock.Hash(), firstNonPrunedBlock.NumberU64()) {
  2311. t.Errorf("Block %d pruned", firstNonPrunedBlock.NumberU64())
  2312. }
  2313. // Now re-import some old blocks
  2314. blockToReimport := blocks[5:8]
  2315. _, err = chain.InsertChain(blockToReimport)
  2316. if err != nil {
  2317. t.Errorf("Got error, %v", err)
  2318. }
  2319. }
  2320. // TestDeleteCreateRevert tests a weird state transition corner case that we hit
  2321. // while changing the internals of statedb. The workflow is that a contract is
  2322. // self destructed, then in a followup transaction (but same block) it's created
  2323. // again and the transaction reverted.
  2324. //
  2325. // The original statedb implementation flushed dirty objects to the tries after
  2326. // each transaction, so this works ok. The rework accumulated writes in memory
  2327. // first, but the journal wiped the entire state object on create-revert.
  2328. func TestDeleteCreateRevert(t *testing.T) {
  2329. var (
  2330. aa = common.HexToAddress("0x000000000000000000000000000000000000aaaa")
  2331. bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
  2332. // Generate a canonical chain to act as the main dataset
  2333. engine = ethash.NewFaker()
  2334. db = rawdb.NewMemoryDatabase()
  2335. // A sender who makes transactions, has some funds
  2336. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2337. address = crypto.PubkeyToAddress(key.PublicKey)
  2338. funds = big.NewInt(1000000000)
  2339. gspec = &Genesis{
  2340. Config: params.TestChainConfig,
  2341. Alloc: GenesisAlloc{
  2342. address: {Balance: funds},
  2343. // The address 0xAAAAA selfdestructs if called
  2344. aa: {
  2345. // Code needs to just selfdestruct
  2346. Code: []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)},
  2347. Nonce: 1,
  2348. Balance: big.NewInt(0),
  2349. },
  2350. // The address 0xBBBB send 1 wei to 0xAAAA, then reverts
  2351. bb: {
  2352. Code: []byte{
  2353. byte(vm.PC), // [0]
  2354. byte(vm.DUP1), // [0,0]
  2355. byte(vm.DUP1), // [0,0,0]
  2356. byte(vm.DUP1), // [0,0,0,0]
  2357. byte(vm.PUSH1), 0x01, // [0,0,0,0,1] (value)
  2358. byte(vm.PUSH2), 0xaa, 0xaa, // [0,0,0,0,1, 0xaaaa]
  2359. byte(vm.GAS),
  2360. byte(vm.CALL),
  2361. byte(vm.REVERT),
  2362. },
  2363. Balance: big.NewInt(1),
  2364. },
  2365. },
  2366. }
  2367. genesis = gspec.MustCommit(db)
  2368. )
  2369. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 1, func(i int, b *BlockGen) {
  2370. b.SetCoinbase(common.Address{1})
  2371. // One transaction to AAAA
  2372. tx, _ := types.SignTx(types.NewTransaction(0, aa,
  2373. big.NewInt(0), 50000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2374. b.AddTx(tx)
  2375. // One transaction to BBBB
  2376. tx, _ = types.SignTx(types.NewTransaction(1, bb,
  2377. big.NewInt(0), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2378. b.AddTx(tx)
  2379. })
  2380. // Import the canonical chain
  2381. diskdb := rawdb.NewMemoryDatabase()
  2382. gspec.MustCommit(diskdb)
  2383. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
  2384. if err != nil {
  2385. t.Fatalf("failed to create tester chain: %v", err)
  2386. }
  2387. if n, err := chain.InsertChain(blocks); err != nil {
  2388. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2389. }
  2390. }
  2391. // TestDeleteRecreateSlots tests a state-transition that contains both deletion
  2392. // and recreation of contract state.
  2393. // Contract A exists, has slots 1 and 2 set
  2394. // Tx 1: Selfdestruct A
  2395. // Tx 2: Re-create A, set slots 3 and 4
  2396. // Expected outcome is that _all_ slots are cleared from A, due to the selfdestruct,
  2397. // and then the new slots exist
  2398. func TestDeleteRecreateSlots(t *testing.T) {
  2399. var (
  2400. // Generate a canonical chain to act as the main dataset
  2401. engine = ethash.NewFaker()
  2402. db = rawdb.NewMemoryDatabase()
  2403. // A sender who makes transactions, has some funds
  2404. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2405. address = crypto.PubkeyToAddress(key.PublicKey)
  2406. funds = big.NewInt(1000000000)
  2407. bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
  2408. aaStorage = make(map[common.Hash]common.Hash) // Initial storage in AA
  2409. aaCode = []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)} // Code for AA (simple selfdestruct)
  2410. )
  2411. // Populate two slots
  2412. aaStorage[common.HexToHash("01")] = common.HexToHash("01")
  2413. aaStorage[common.HexToHash("02")] = common.HexToHash("02")
  2414. // The bb-code needs to CREATE2 the aa contract. It consists of
  2415. // both initcode and deployment code
  2416. // initcode:
  2417. // 1. Set slots 3=3, 4=4,
  2418. // 2. Return aaCode
  2419. initCode := []byte{
  2420. byte(vm.PUSH1), 0x3, // value
  2421. byte(vm.PUSH1), 0x3, // location
  2422. byte(vm.SSTORE), // Set slot[3] = 1
  2423. byte(vm.PUSH1), 0x4, // value
  2424. byte(vm.PUSH1), 0x4, // location
  2425. byte(vm.SSTORE), // Set slot[4] = 1
  2426. // Slots are set, now return the code
  2427. byte(vm.PUSH2), byte(vm.PC), byte(vm.SELFDESTRUCT), // Push code on stack
  2428. byte(vm.PUSH1), 0x0, // memory start on stack
  2429. byte(vm.MSTORE),
  2430. // Code is now in memory.
  2431. byte(vm.PUSH1), 0x2, // size
  2432. byte(vm.PUSH1), byte(32 - 2), // offset
  2433. byte(vm.RETURN),
  2434. }
  2435. if l := len(initCode); l > 32 {
  2436. t.Fatalf("init code is too long for a pushx, need a more elaborate deployer")
  2437. }
  2438. bbCode := []byte{
  2439. // Push initcode onto stack
  2440. byte(vm.PUSH1) + byte(len(initCode)-1)}
  2441. bbCode = append(bbCode, initCode...)
  2442. bbCode = append(bbCode, []byte{
  2443. byte(vm.PUSH1), 0x0, // memory start on stack
  2444. byte(vm.MSTORE),
  2445. byte(vm.PUSH1), 0x00, // salt
  2446. byte(vm.PUSH1), byte(len(initCode)), // size
  2447. byte(vm.PUSH1), byte(32 - len(initCode)), // offset
  2448. byte(vm.PUSH1), 0x00, // endowment
  2449. byte(vm.CREATE2),
  2450. }...)
  2451. initHash := crypto.Keccak256Hash(initCode)
  2452. aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:])
  2453. t.Logf("Destination address: %x\n", aa)
  2454. gspec := &Genesis{
  2455. Config: params.TestChainConfig,
  2456. Alloc: GenesisAlloc{
  2457. address: {Balance: funds},
  2458. // The address 0xAAAAA selfdestructs if called
  2459. aa: {
  2460. // Code needs to just selfdestruct
  2461. Code: aaCode,
  2462. Nonce: 1,
  2463. Balance: big.NewInt(0),
  2464. Storage: aaStorage,
  2465. },
  2466. // The contract BB recreates AA
  2467. bb: {
  2468. Code: bbCode,
  2469. Balance: big.NewInt(1),
  2470. },
  2471. },
  2472. }
  2473. genesis := gspec.MustCommit(db)
  2474. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 1, func(i int, b *BlockGen) {
  2475. b.SetCoinbase(common.Address{1})
  2476. // One transaction to AA, to kill it
  2477. tx, _ := types.SignTx(types.NewTransaction(0, aa,
  2478. big.NewInt(0), 50000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2479. b.AddTx(tx)
  2480. // One transaction to BB, to recreate AA
  2481. tx, _ = types.SignTx(types.NewTransaction(1, bb,
  2482. big.NewInt(0), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2483. b.AddTx(tx)
  2484. })
  2485. // Import the canonical chain
  2486. diskdb := rawdb.NewMemoryDatabase()
  2487. gspec.MustCommit(diskdb)
  2488. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
  2489. Debug: true,
  2490. Tracer: vm.NewJSONLogger(nil, os.Stdout),
  2491. }, nil, nil)
  2492. if err != nil {
  2493. t.Fatalf("failed to create tester chain: %v", err)
  2494. }
  2495. if n, err := chain.InsertChain(blocks); err != nil {
  2496. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2497. }
  2498. statedb, _ := chain.State()
  2499. // If all is correct, then slot 1 and 2 are zero
  2500. if got, exp := statedb.GetState(aa, common.HexToHash("01")), (common.Hash{}); got != exp {
  2501. t.Errorf("got %x exp %x", got, exp)
  2502. }
  2503. if got, exp := statedb.GetState(aa, common.HexToHash("02")), (common.Hash{}); got != exp {
  2504. t.Errorf("got %x exp %x", got, exp)
  2505. }
  2506. // Also, 3 and 4 should be set
  2507. if got, exp := statedb.GetState(aa, common.HexToHash("03")), common.HexToHash("03"); got != exp {
  2508. t.Fatalf("got %x exp %x", got, exp)
  2509. }
  2510. if got, exp := statedb.GetState(aa, common.HexToHash("04")), common.HexToHash("04"); got != exp {
  2511. t.Fatalf("got %x exp %x", got, exp)
  2512. }
  2513. }
  2514. // TestDeleteRecreateAccount tests a state-transition that contains deletion of a
  2515. // contract with storage, and a recreate of the same contract via a
  2516. // regular value-transfer
  2517. // Expected outcome is that _all_ slots are cleared from A
  2518. func TestDeleteRecreateAccount(t *testing.T) {
  2519. var (
  2520. // Generate a canonical chain to act as the main dataset
  2521. engine = ethash.NewFaker()
  2522. db = rawdb.NewMemoryDatabase()
  2523. // A sender who makes transactions, has some funds
  2524. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2525. address = crypto.PubkeyToAddress(key.PublicKey)
  2526. funds = big.NewInt(1000000000)
  2527. aa = common.HexToAddress("0x7217d81b76bdd8707601e959454e3d776aee5f43")
  2528. aaStorage = make(map[common.Hash]common.Hash) // Initial storage in AA
  2529. aaCode = []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)} // Code for AA (simple selfdestruct)
  2530. )
  2531. // Populate two slots
  2532. aaStorage[common.HexToHash("01")] = common.HexToHash("01")
  2533. aaStorage[common.HexToHash("02")] = common.HexToHash("02")
  2534. gspec := &Genesis{
  2535. Config: params.TestChainConfig,
  2536. Alloc: GenesisAlloc{
  2537. address: {Balance: funds},
  2538. // The address 0xAAAAA selfdestructs if called
  2539. aa: {
  2540. // Code needs to just selfdestruct
  2541. Code: aaCode,
  2542. Nonce: 1,
  2543. Balance: big.NewInt(0),
  2544. Storage: aaStorage,
  2545. },
  2546. },
  2547. }
  2548. genesis := gspec.MustCommit(db)
  2549. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 1, func(i int, b *BlockGen) {
  2550. b.SetCoinbase(common.Address{1})
  2551. // One transaction to AA, to kill it
  2552. tx, _ := types.SignTx(types.NewTransaction(0, aa,
  2553. big.NewInt(0), 50000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2554. b.AddTx(tx)
  2555. // One transaction to AA, to recreate it (but without storage
  2556. tx, _ = types.SignTx(types.NewTransaction(1, aa,
  2557. big.NewInt(1), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2558. b.AddTx(tx)
  2559. })
  2560. // Import the canonical chain
  2561. diskdb := rawdb.NewMemoryDatabase()
  2562. gspec.MustCommit(diskdb)
  2563. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
  2564. Debug: true,
  2565. Tracer: vm.NewJSONLogger(nil, os.Stdout),
  2566. }, nil, nil)
  2567. if err != nil {
  2568. t.Fatalf("failed to create tester chain: %v", err)
  2569. }
  2570. if n, err := chain.InsertChain(blocks); err != nil {
  2571. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2572. }
  2573. statedb, _ := chain.State()
  2574. // If all is correct, then both slots are zero
  2575. if got, exp := statedb.GetState(aa, common.HexToHash("01")), (common.Hash{}); got != exp {
  2576. t.Errorf("got %x exp %x", got, exp)
  2577. }
  2578. if got, exp := statedb.GetState(aa, common.HexToHash("02")), (common.Hash{}); got != exp {
  2579. t.Errorf("got %x exp %x", got, exp)
  2580. }
  2581. }
  2582. // TestDeleteRecreateSlotsAcrossManyBlocks tests multiple state-transition that contains both deletion
  2583. // and recreation of contract state.
  2584. // Contract A exists, has slots 1 and 2 set
  2585. // Tx 1: Selfdestruct A
  2586. // Tx 2: Re-create A, set slots 3 and 4
  2587. // Expected outcome is that _all_ slots are cleared from A, due to the selfdestruct,
  2588. // and then the new slots exist
  2589. func TestDeleteRecreateSlotsAcrossManyBlocks(t *testing.T) {
  2590. var (
  2591. // Generate a canonical chain to act as the main dataset
  2592. engine = ethash.NewFaker()
  2593. db = rawdb.NewMemoryDatabase()
  2594. // A sender who makes transactions, has some funds
  2595. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2596. address = crypto.PubkeyToAddress(key.PublicKey)
  2597. funds = big.NewInt(1000000000)
  2598. bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
  2599. aaStorage = make(map[common.Hash]common.Hash) // Initial storage in AA
  2600. aaCode = []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)} // Code for AA (simple selfdestruct)
  2601. )
  2602. // Populate two slots
  2603. aaStorage[common.HexToHash("01")] = common.HexToHash("01")
  2604. aaStorage[common.HexToHash("02")] = common.HexToHash("02")
  2605. // The bb-code needs to CREATE2 the aa contract. It consists of
  2606. // both initcode and deployment code
  2607. // initcode:
  2608. // 1. Set slots 3=blocknum+1, 4=4,
  2609. // 2. Return aaCode
  2610. initCode := []byte{
  2611. byte(vm.PUSH1), 0x1, //
  2612. byte(vm.NUMBER), // value = number + 1
  2613. byte(vm.ADD), //
  2614. byte(vm.PUSH1), 0x3, // location
  2615. byte(vm.SSTORE), // Set slot[3] = number + 1
  2616. byte(vm.PUSH1), 0x4, // value
  2617. byte(vm.PUSH1), 0x4, // location
  2618. byte(vm.SSTORE), // Set slot[4] = 4
  2619. // Slots are set, now return the code
  2620. byte(vm.PUSH2), byte(vm.PC), byte(vm.SELFDESTRUCT), // Push code on stack
  2621. byte(vm.PUSH1), 0x0, // memory start on stack
  2622. byte(vm.MSTORE),
  2623. // Code is now in memory.
  2624. byte(vm.PUSH1), 0x2, // size
  2625. byte(vm.PUSH1), byte(32 - 2), // offset
  2626. byte(vm.RETURN),
  2627. }
  2628. if l := len(initCode); l > 32 {
  2629. t.Fatalf("init code is too long for a pushx, need a more elaborate deployer")
  2630. }
  2631. bbCode := []byte{
  2632. // Push initcode onto stack
  2633. byte(vm.PUSH1) + byte(len(initCode)-1)}
  2634. bbCode = append(bbCode, initCode...)
  2635. bbCode = append(bbCode, []byte{
  2636. byte(vm.PUSH1), 0x0, // memory start on stack
  2637. byte(vm.MSTORE),
  2638. byte(vm.PUSH1), 0x00, // salt
  2639. byte(vm.PUSH1), byte(len(initCode)), // size
  2640. byte(vm.PUSH1), byte(32 - len(initCode)), // offset
  2641. byte(vm.PUSH1), 0x00, // endowment
  2642. byte(vm.CREATE2),
  2643. }...)
  2644. initHash := crypto.Keccak256Hash(initCode)
  2645. aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:])
  2646. t.Logf("Destination address: %x\n", aa)
  2647. gspec := &Genesis{
  2648. Config: params.TestChainConfig,
  2649. Alloc: GenesisAlloc{
  2650. address: {Balance: funds},
  2651. // The address 0xAAAAA selfdestructs if called
  2652. aa: {
  2653. // Code needs to just selfdestruct
  2654. Code: aaCode,
  2655. Nonce: 1,
  2656. Balance: big.NewInt(0),
  2657. Storage: aaStorage,
  2658. },
  2659. // The contract BB recreates AA
  2660. bb: {
  2661. Code: bbCode,
  2662. Balance: big.NewInt(1),
  2663. },
  2664. },
  2665. }
  2666. genesis := gspec.MustCommit(db)
  2667. var nonce uint64
  2668. type expectation struct {
  2669. exist bool
  2670. blocknum int
  2671. values map[int]int
  2672. }
  2673. var current = &expectation{
  2674. exist: true, // exists in genesis
  2675. blocknum: 0,
  2676. values: map[int]int{1: 1, 2: 2},
  2677. }
  2678. var expectations []*expectation
  2679. var newDestruct = func(e *expectation) *types.Transaction {
  2680. tx, _ := types.SignTx(types.NewTransaction(nonce, aa,
  2681. big.NewInt(0), 50000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2682. nonce++
  2683. if e.exist {
  2684. e.exist = false
  2685. e.values = nil
  2686. }
  2687. t.Logf("block %d; adding destruct\n", e.blocknum)
  2688. return tx
  2689. }
  2690. var newResurrect = func(e *expectation) *types.Transaction {
  2691. tx, _ := types.SignTx(types.NewTransaction(nonce, bb,
  2692. big.NewInt(0), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2693. nonce++
  2694. if !e.exist {
  2695. e.exist = true
  2696. e.values = map[int]int{3: e.blocknum + 1, 4: 4}
  2697. }
  2698. t.Logf("block %d; adding resurrect\n", e.blocknum)
  2699. return tx
  2700. }
  2701. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 150, func(i int, b *BlockGen) {
  2702. var exp = new(expectation)
  2703. exp.blocknum = i + 1
  2704. exp.values = make(map[int]int)
  2705. for k, v := range current.values {
  2706. exp.values[k] = v
  2707. }
  2708. exp.exist = current.exist
  2709. b.SetCoinbase(common.Address{1})
  2710. if i%2 == 0 {
  2711. b.AddTx(newDestruct(exp))
  2712. }
  2713. if i%3 == 0 {
  2714. b.AddTx(newResurrect(exp))
  2715. }
  2716. if i%5 == 0 {
  2717. b.AddTx(newDestruct(exp))
  2718. }
  2719. if i%7 == 0 {
  2720. b.AddTx(newResurrect(exp))
  2721. }
  2722. expectations = append(expectations, exp)
  2723. current = exp
  2724. })
  2725. // Import the canonical chain
  2726. diskdb := rawdb.NewMemoryDatabase()
  2727. gspec.MustCommit(diskdb)
  2728. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
  2729. //Debug: true,
  2730. //Tracer: vm.NewJSONLogger(nil, os.Stdout),
  2731. }, nil, nil)
  2732. if err != nil {
  2733. t.Fatalf("failed to create tester chain: %v", err)
  2734. }
  2735. var asHash = func(num int) common.Hash {
  2736. return common.BytesToHash([]byte{byte(num)})
  2737. }
  2738. for i, block := range blocks {
  2739. blockNum := i + 1
  2740. if n, err := chain.InsertChain([]*types.Block{block}); err != nil {
  2741. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2742. }
  2743. statedb, _ := chain.State()
  2744. // If all is correct, then slot 1 and 2 are zero
  2745. if got, exp := statedb.GetState(aa, common.HexToHash("01")), (common.Hash{}); got != exp {
  2746. t.Errorf("block %d, got %x exp %x", blockNum, got, exp)
  2747. }
  2748. if got, exp := statedb.GetState(aa, common.HexToHash("02")), (common.Hash{}); got != exp {
  2749. t.Errorf("block %d, got %x exp %x", blockNum, got, exp)
  2750. }
  2751. exp := expectations[i]
  2752. if exp.exist {
  2753. if !statedb.Exist(aa) {
  2754. t.Fatalf("block %d, expected %v to exist, it did not", blockNum, aa)
  2755. }
  2756. for slot, val := range exp.values {
  2757. if gotValue, expValue := statedb.GetState(aa, asHash(slot)), asHash(val); gotValue != expValue {
  2758. t.Fatalf("block %d, slot %d, got %x exp %x", blockNum, slot, gotValue, expValue)
  2759. }
  2760. }
  2761. } else {
  2762. if statedb.Exist(aa) {
  2763. t.Fatalf("block %d, expected %v to not exist, it did", blockNum, aa)
  2764. }
  2765. }
  2766. }
  2767. }
  2768. // TestInitThenFailCreateContract tests a pretty notorious case that happened
  2769. // on mainnet over blocks 7338108, 7338110 and 7338115.
  2770. // - Block 7338108: address e771789f5cccac282f23bb7add5690e1f6ca467c is initiated
  2771. // with 0.001 ether (thus created but no code)
  2772. // - Block 7338110: a CREATE2 is attempted. The CREATE2 would deploy code on
  2773. // the same address e771789f5cccac282f23bb7add5690e1f6ca467c. However, the
  2774. // deployment fails due to OOG during initcode execution
  2775. // - Block 7338115: another tx checks the balance of
  2776. // e771789f5cccac282f23bb7add5690e1f6ca467c, and the snapshotter returned it as
  2777. // zero.
  2778. //
  2779. // The problem being that the snapshotter maintains a destructset, and adds items
  2780. // to the destructset in case something is created "onto" an existing item.
  2781. // We need to either roll back the snapDestructs, or not place it into snapDestructs
  2782. // in the first place.
  2783. //
  2784. func TestInitThenFailCreateContract(t *testing.T) {
  2785. var (
  2786. // Generate a canonical chain to act as the main dataset
  2787. engine = ethash.NewFaker()
  2788. db = rawdb.NewMemoryDatabase()
  2789. // A sender who makes transactions, has some funds
  2790. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2791. address = crypto.PubkeyToAddress(key.PublicKey)
  2792. funds = big.NewInt(1000000000)
  2793. bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
  2794. )
  2795. // The bb-code needs to CREATE2 the aa contract. It consists of
  2796. // both initcode and deployment code
  2797. // initcode:
  2798. // 1. If blocknum < 1, error out (e.g invalid opcode)
  2799. // 2. else, return a snippet of code
  2800. initCode := []byte{
  2801. byte(vm.PUSH1), 0x1, // y (2)
  2802. byte(vm.NUMBER), // x (number)
  2803. byte(vm.GT), // x > y?
  2804. byte(vm.PUSH1), byte(0x8),
  2805. byte(vm.JUMPI), // jump to label if number > 2
  2806. byte(0xFE), // illegal opcode
  2807. byte(vm.JUMPDEST),
  2808. byte(vm.PUSH1), 0x2, // size
  2809. byte(vm.PUSH1), 0x0, // offset
  2810. byte(vm.RETURN), // return 2 bytes of zero-code
  2811. }
  2812. if l := len(initCode); l > 32 {
  2813. t.Fatalf("init code is too long for a pushx, need a more elaborate deployer")
  2814. }
  2815. bbCode := []byte{
  2816. // Push initcode onto stack
  2817. byte(vm.PUSH1) + byte(len(initCode)-1)}
  2818. bbCode = append(bbCode, initCode...)
  2819. bbCode = append(bbCode, []byte{
  2820. byte(vm.PUSH1), 0x0, // memory start on stack
  2821. byte(vm.MSTORE),
  2822. byte(vm.PUSH1), 0x00, // salt
  2823. byte(vm.PUSH1), byte(len(initCode)), // size
  2824. byte(vm.PUSH1), byte(32 - len(initCode)), // offset
  2825. byte(vm.PUSH1), 0x00, // endowment
  2826. byte(vm.CREATE2),
  2827. }...)
  2828. initHash := crypto.Keccak256Hash(initCode)
  2829. aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:])
  2830. t.Logf("Destination address: %x\n", aa)
  2831. gspec := &Genesis{
  2832. Config: params.TestChainConfig,
  2833. Alloc: GenesisAlloc{
  2834. address: {Balance: funds},
  2835. // The address aa has some funds
  2836. aa: {Balance: big.NewInt(100000)},
  2837. // The contract BB tries to create code onto AA
  2838. bb: {
  2839. Code: bbCode,
  2840. Balance: big.NewInt(1),
  2841. },
  2842. },
  2843. }
  2844. genesis := gspec.MustCommit(db)
  2845. nonce := uint64(0)
  2846. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 4, func(i int, b *BlockGen) {
  2847. b.SetCoinbase(common.Address{1})
  2848. // One transaction to BB
  2849. tx, _ := types.SignTx(types.NewTransaction(nonce, bb,
  2850. big.NewInt(0), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2851. b.AddTx(tx)
  2852. nonce++
  2853. })
  2854. // Import the canonical chain
  2855. diskdb := rawdb.NewMemoryDatabase()
  2856. gspec.MustCommit(diskdb)
  2857. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
  2858. //Debug: true,
  2859. //Tracer: vm.NewJSONLogger(nil, os.Stdout),
  2860. }, nil, nil)
  2861. if err != nil {
  2862. t.Fatalf("failed to create tester chain: %v", err)
  2863. }
  2864. statedb, _ := chain.State()
  2865. if got, exp := statedb.GetBalance(aa), big.NewInt(100000); got.Cmp(exp) != 0 {
  2866. t.Fatalf("Genesis err, got %v exp %v", got, exp)
  2867. }
  2868. // First block tries to create, but fails
  2869. {
  2870. block := blocks[0]
  2871. if _, err := chain.InsertChain([]*types.Block{blocks[0]}); err != nil {
  2872. t.Fatalf("block %d: failed to insert into chain: %v", block.NumberU64(), err)
  2873. }
  2874. statedb, _ = chain.State()
  2875. if got, exp := statedb.GetBalance(aa), big.NewInt(100000); got.Cmp(exp) != 0 {
  2876. t.Fatalf("block %d: got %v exp %v", block.NumberU64(), got, exp)
  2877. }
  2878. }
  2879. // Import the rest of the blocks
  2880. for _, block := range blocks[1:] {
  2881. if _, err := chain.InsertChain([]*types.Block{block}); err != nil {
  2882. t.Fatalf("block %d: failed to insert into chain: %v", block.NumberU64(), err)
  2883. }
  2884. }
  2885. }
  2886. // TestEIP2718Transition tests that an EIP-2718 transaction will be accepted
  2887. // after the fork block has passed. This is verified by sending an EIP-2930
  2888. // access list transaction, which specifies a single slot access, and then
  2889. // checking that the gas usage of a hot SLOAD and a cold SLOAD are calculated
  2890. // correctly.
  2891. func TestEIP2718Transition(t *testing.T) {
  2892. var (
  2893. aa = common.HexToAddress("0x000000000000000000000000000000000000aaaa")
  2894. // Generate a canonical chain to act as the main dataset
  2895. engine = ethash.NewFaker()
  2896. db = rawdb.NewMemoryDatabase()
  2897. // A sender who makes transactions, has some funds
  2898. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2899. address = crypto.PubkeyToAddress(key.PublicKey)
  2900. funds = big.NewInt(1000000000)
  2901. gspec = &Genesis{
  2902. Config: params.YoloV3ChainConfig,
  2903. Alloc: GenesisAlloc{
  2904. address: {Balance: funds},
  2905. // The address 0xAAAA sloads 0x00 and 0x01
  2906. aa: {
  2907. Code: []byte{
  2908. byte(vm.PC),
  2909. byte(vm.PC),
  2910. byte(vm.SLOAD),
  2911. byte(vm.SLOAD),
  2912. },
  2913. Nonce: 0,
  2914. Balance: big.NewInt(0),
  2915. },
  2916. },
  2917. }
  2918. genesis = gspec.MustCommit(db)
  2919. )
  2920. blocks, _ := GenerateChain(gspec.Config, genesis, engine, db, 1, func(i int, b *BlockGen) {
  2921. b.SetCoinbase(common.Address{1})
  2922. // One transaction to 0xAAAA
  2923. signer := types.LatestSigner(gspec.Config)
  2924. tx, _ := types.SignNewTx(key, signer, &types.AccessListTx{
  2925. ChainID: gspec.Config.ChainID,
  2926. Nonce: 0,
  2927. To: &aa,
  2928. Gas: 30000,
  2929. GasPrice: big.NewInt(1),
  2930. AccessList: types.AccessList{{
  2931. Address: aa,
  2932. StorageKeys: []common.Hash{{0}},
  2933. }},
  2934. })
  2935. b.AddTx(tx)
  2936. })
  2937. // Import the canonical chain
  2938. diskdb := rawdb.NewMemoryDatabase()
  2939. gspec.MustCommit(diskdb)
  2940. chain, err := NewBlockChain(diskdb, nil, gspec.Config, engine, vm.Config{}, nil, nil)
  2941. if err != nil {
  2942. t.Fatalf("failed to create tester chain: %v", err)
  2943. }
  2944. if n, err := chain.InsertChain(blocks); err != nil {
  2945. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2946. }
  2947. block := chain.GetBlockByNumber(1)
  2948. // Expected gas is intrinsic + 2 * pc + hot load + cold load, since only one load is in the access list
  2949. expected := params.TxGas + params.TxAccessListAddressGas + params.TxAccessListStorageKeyGas + vm.GasQuickStep*2 + vm.WarmStorageReadCostEIP2929 + vm.ColdSloadCostEIP2929
  2950. if block.GasUsed() != expected {
  2951. t.Fatalf("incorrect amount of gas spent: expected %d, got %d", expected, block.GasUsed())
  2952. }
  2953. }