blockchain_test.go 115 KB

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