blockchain_test.go 112 KB

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