blockchain_test.go 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884
  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. "reflect"
  24. "sync"
  25. "testing"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/consensus"
  29. "github.com/ethereum/go-ethereum/consensus/ethash"
  30. "github.com/ethereum/go-ethereum/core/rawdb"
  31. "github.com/ethereum/go-ethereum/core/state"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/core/vm"
  34. "github.com/ethereum/go-ethereum/crypto"
  35. "github.com/ethereum/go-ethereum/ethdb"
  36. "github.com/ethereum/go-ethereum/params"
  37. )
  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)
  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)
  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)
  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)
  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)
  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()) != types.DeriveSha(arblock.Transactions()) || types.DeriveSha(anblock.Transactions()) != types.DeriveSha(arblock.Transactions()) {
  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) != types.DeriveSha(areceipts) {
  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 := []common.Hash{}
  672. for _, block := range blocks[height/2:] {
  673. remove = append(remove, block.Hash())
  674. }
  675. // Create a small assertion method to check the three heads
  676. assert := func(t *testing.T, kind string, chain *BlockChain, header uint64, fast uint64, block uint64) {
  677. if num := chain.CurrentBlock().NumberU64(); num != block {
  678. t.Errorf("%s head block mismatch: have #%v, want #%v", kind, num, block)
  679. }
  680. if num := chain.CurrentFastBlock().NumberU64(); num != fast {
  681. t.Errorf("%s head fast-block mismatch: have #%v, want #%v", kind, num, fast)
  682. }
  683. if num := chain.CurrentHeader().Number.Uint64(); num != header {
  684. t.Errorf("%s head header mismatch: have #%v, want #%v", kind, num, header)
  685. }
  686. }
  687. // Import the chain as an archive node and ensure all pointers are updated
  688. archiveDb, delfn := makeDb()
  689. defer delfn()
  690. archive, _ := NewBlockChain(archiveDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, 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.Rollback(remove)
  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)
  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.Rollback(remove)
  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)
  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.Rollback(remove)
  729. assert(t, "ancient", ancient, height/2, height/2, 0)
  730. if frozen, err := ancientDb.Ancients(); err != nil || frozen != height/2+1 {
  731. t.Fatalf("failed to truncate ancient store, want %v, have %v", height/2+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)
  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.Rollback(remove)
  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)
  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)
  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. func TestLogRebirth(t *testing.T) {
  895. var (
  896. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  897. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  898. db = rawdb.NewMemoryDatabase()
  899. // this code generates a log
  900. code = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
  901. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}}}
  902. genesis = gspec.MustCommit(db)
  903. signer = types.NewEIP155Signer(gspec.Config.ChainID)
  904. newLogCh = make(chan bool)
  905. removeLogCh = make(chan bool)
  906. )
  907. // validateLogEvent checks whether the received logs number is equal with expected.
  908. validateLogEvent := func(sink interface{}, result chan bool, expect int) {
  909. chanval := reflect.ValueOf(sink)
  910. chantyp := chanval.Type()
  911. if chantyp.Kind() != reflect.Chan || chantyp.ChanDir()&reflect.RecvDir == 0 {
  912. t.Fatalf("invalid channel, given type %v", chantyp)
  913. }
  914. cnt := 0
  915. var recv []reflect.Value
  916. timeout := time.After(1 * time.Second)
  917. cases := []reflect.SelectCase{{Chan: chanval, Dir: reflect.SelectRecv}, {Chan: reflect.ValueOf(timeout), Dir: reflect.SelectRecv}}
  918. for {
  919. chose, v, _ := reflect.Select(cases)
  920. if chose == 1 {
  921. // Not enough event received
  922. result <- false
  923. return
  924. }
  925. cnt += 1
  926. recv = append(recv, v)
  927. if cnt == expect {
  928. break
  929. }
  930. }
  931. done := time.After(50 * time.Millisecond)
  932. cases = cases[:1]
  933. cases = append(cases, reflect.SelectCase{Chan: reflect.ValueOf(done), Dir: reflect.SelectRecv})
  934. chose, _, _ := reflect.Select(cases)
  935. // If chose equal 0, it means receiving redundant events.
  936. if chose == 1 {
  937. result <- true
  938. } else {
  939. result <- false
  940. }
  941. }
  942. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil)
  943. defer blockchain.Stop()
  944. logsCh := make(chan []*types.Log)
  945. blockchain.SubscribeLogsEvent(logsCh)
  946. rmLogsCh := make(chan RemovedLogsEvent)
  947. blockchain.SubscribeRemovedLogsEvent(rmLogsCh)
  948. chain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) {
  949. if i == 1 {
  950. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), code), signer, key1)
  951. if err != nil {
  952. t.Fatalf("failed to create tx: %v", err)
  953. }
  954. gen.AddTx(tx)
  955. }
  956. })
  957. // Spawn a goroutine to receive log events
  958. go validateLogEvent(logsCh, newLogCh, 1)
  959. if _, err := blockchain.InsertChain(chain); err != nil {
  960. t.Fatalf("failed to insert chain: %v", err)
  961. }
  962. if !<-newLogCh {
  963. t.Fatal("failed to receive new log event")
  964. }
  965. // Generate long reorg chain
  966. forkChain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) {
  967. if i == 1 {
  968. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), code), signer, key1)
  969. if err != nil {
  970. t.Fatalf("failed to create tx: %v", err)
  971. }
  972. gen.AddTx(tx)
  973. // Higher block difficulty
  974. gen.OffsetTime(-9)
  975. }
  976. })
  977. // Spawn a goroutine to receive log events
  978. go validateLogEvent(logsCh, newLogCh, 1)
  979. go validateLogEvent(rmLogsCh, removeLogCh, 1)
  980. if _, err := blockchain.InsertChain(forkChain); err != nil {
  981. t.Fatalf("failed to insert forked chain: %v", err)
  982. }
  983. if !<-newLogCh {
  984. t.Fatal("failed to receive new log event")
  985. }
  986. if !<-removeLogCh {
  987. t.Fatal("failed to receive removed log event")
  988. }
  989. newBlocks, _ := GenerateChain(params.TestChainConfig, chain[len(chain)-1], ethash.NewFaker(), db, 1, func(i int, gen *BlockGen) {})
  990. go validateLogEvent(logsCh, newLogCh, 1)
  991. go validateLogEvent(rmLogsCh, removeLogCh, 1)
  992. if _, err := blockchain.InsertChain(newBlocks); err != nil {
  993. t.Fatalf("failed to insert forked chain: %v", err)
  994. }
  995. // Rebirth logs should omit a newLogEvent
  996. if !<-newLogCh {
  997. t.Fatal("failed to receive new log event")
  998. }
  999. // Ensure removedLog events received
  1000. if !<-removeLogCh {
  1001. t.Fatal("failed to receive removed log event")
  1002. }
  1003. }
  1004. func TestSideLogRebirth(t *testing.T) {
  1005. var (
  1006. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1007. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  1008. db = rawdb.NewMemoryDatabase()
  1009. // this code generates a log
  1010. code = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
  1011. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}}}
  1012. genesis = gspec.MustCommit(db)
  1013. signer = types.NewEIP155Signer(gspec.Config.ChainID)
  1014. newLogCh = make(chan bool)
  1015. )
  1016. // listenNewLog checks whether the received logs number is equal with expected.
  1017. listenNewLog := func(sink chan []*types.Log, expect int) {
  1018. cnt := 0
  1019. for {
  1020. select {
  1021. case logs := <-sink:
  1022. cnt += len(logs)
  1023. case <-time.NewTimer(5 * time.Second).C:
  1024. // new logs timeout
  1025. newLogCh <- false
  1026. return
  1027. }
  1028. if cnt == expect {
  1029. break
  1030. } else if cnt > expect {
  1031. // redundant logs received
  1032. newLogCh <- false
  1033. return
  1034. }
  1035. }
  1036. select {
  1037. case <-sink:
  1038. // redundant logs received
  1039. newLogCh <- false
  1040. case <-time.NewTimer(100 * time.Millisecond).C:
  1041. newLogCh <- true
  1042. }
  1043. }
  1044. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil)
  1045. defer blockchain.Stop()
  1046. logsCh := make(chan []*types.Log)
  1047. blockchain.SubscribeLogsEvent(logsCh)
  1048. chain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) {
  1049. if i == 1 {
  1050. // Higher block difficulty
  1051. gen.OffsetTime(-9)
  1052. }
  1053. })
  1054. if _, err := blockchain.InsertChain(chain); err != nil {
  1055. t.Fatalf("failed to insert forked chain: %v", err)
  1056. }
  1057. // Generate side chain with lower difficulty
  1058. sideChain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) {
  1059. if i == 1 {
  1060. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), code), signer, key1)
  1061. if err != nil {
  1062. t.Fatalf("failed to create tx: %v", err)
  1063. }
  1064. gen.AddTx(tx)
  1065. }
  1066. })
  1067. if _, err := blockchain.InsertChain(sideChain); err != nil {
  1068. t.Fatalf("failed to insert forked chain: %v", err)
  1069. }
  1070. // Generate a new block based on side chain
  1071. newBlocks, _ := GenerateChain(params.TestChainConfig, sideChain[len(sideChain)-1], ethash.NewFaker(), db, 1, func(i int, gen *BlockGen) {})
  1072. go listenNewLog(logsCh, 1)
  1073. if _, err := blockchain.InsertChain(newBlocks); err != nil {
  1074. t.Fatalf("failed to insert forked chain: %v", err)
  1075. }
  1076. // Rebirth logs should omit a newLogEvent
  1077. if !<-newLogCh {
  1078. t.Fatalf("failed to receive new log event")
  1079. }
  1080. }
  1081. func TestReorgSideEvent(t *testing.T) {
  1082. var (
  1083. db = rawdb.NewMemoryDatabase()
  1084. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1085. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  1086. gspec = &Genesis{
  1087. Config: params.TestChainConfig,
  1088. Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}},
  1089. }
  1090. genesis = gspec.MustCommit(db)
  1091. signer = types.NewEIP155Signer(gspec.Config.ChainID)
  1092. )
  1093. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil)
  1094. defer blockchain.Stop()
  1095. chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {})
  1096. if _, err := blockchain.InsertChain(chain); err != nil {
  1097. t.Fatalf("failed to insert chain: %v", err)
  1098. }
  1099. replacementBlocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 4, func(i int, gen *BlockGen) {
  1100. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), nil), signer, key1)
  1101. if i == 2 {
  1102. gen.OffsetTime(-9)
  1103. }
  1104. if err != nil {
  1105. t.Fatalf("failed to create tx: %v", err)
  1106. }
  1107. gen.AddTx(tx)
  1108. })
  1109. chainSideCh := make(chan ChainSideEvent, 64)
  1110. blockchain.SubscribeChainSideEvent(chainSideCh)
  1111. if _, err := blockchain.InsertChain(replacementBlocks); err != nil {
  1112. t.Fatalf("failed to insert chain: %v", err)
  1113. }
  1114. // first two block of the secondary chain are for a brief moment considered
  1115. // side chains because up to that point the first one is considered the
  1116. // heavier chain.
  1117. expectedSideHashes := map[common.Hash]bool{
  1118. replacementBlocks[0].Hash(): true,
  1119. replacementBlocks[1].Hash(): true,
  1120. chain[0].Hash(): true,
  1121. chain[1].Hash(): true,
  1122. chain[2].Hash(): true,
  1123. }
  1124. i := 0
  1125. const timeoutDura = 10 * time.Second
  1126. timeout := time.NewTimer(timeoutDura)
  1127. done:
  1128. for {
  1129. select {
  1130. case ev := <-chainSideCh:
  1131. block := ev.Block
  1132. if _, ok := expectedSideHashes[block.Hash()]; !ok {
  1133. t.Errorf("%d: didn't expect %x to be in side chain", i, block.Hash())
  1134. }
  1135. i++
  1136. if i == len(expectedSideHashes) {
  1137. timeout.Stop()
  1138. break done
  1139. }
  1140. timeout.Reset(timeoutDura)
  1141. case <-timeout.C:
  1142. t.Fatal("Timeout. Possibly not all blocks were triggered for sideevent")
  1143. }
  1144. }
  1145. // make sure no more events are fired
  1146. select {
  1147. case e := <-chainSideCh:
  1148. t.Errorf("unexpected event fired: %v", e)
  1149. case <-time.After(250 * time.Millisecond):
  1150. }
  1151. }
  1152. // Tests if the canonical block can be fetched from the database during chain insertion.
  1153. func TestCanonicalBlockRetrieval(t *testing.T) {
  1154. _, blockchain, err := newCanonical(ethash.NewFaker(), 0, true)
  1155. if err != nil {
  1156. t.Fatalf("failed to create pristine chain: %v", err)
  1157. }
  1158. defer blockchain.Stop()
  1159. chain, _ := GenerateChain(blockchain.chainConfig, blockchain.genesisBlock, ethash.NewFaker(), blockchain.db, 10, func(i int, gen *BlockGen) {})
  1160. var pend sync.WaitGroup
  1161. pend.Add(len(chain))
  1162. for i := range chain {
  1163. go func(block *types.Block) {
  1164. defer pend.Done()
  1165. // try to retrieve a block by its canonical hash and see if the block data can be retrieved.
  1166. for {
  1167. ch := rawdb.ReadCanonicalHash(blockchain.db, block.NumberU64())
  1168. if ch == (common.Hash{}) {
  1169. continue // busy wait for canonical hash to be written
  1170. }
  1171. if ch != block.Hash() {
  1172. t.Errorf("unknown canonical hash, want %s, got %s", block.Hash().Hex(), ch.Hex())
  1173. return
  1174. }
  1175. fb := rawdb.ReadBlock(blockchain.db, ch, block.NumberU64())
  1176. if fb == nil {
  1177. t.Errorf("unable to retrieve block %d for canonical hash: %s", block.NumberU64(), ch.Hex())
  1178. return
  1179. }
  1180. if fb.Hash() != block.Hash() {
  1181. t.Errorf("invalid block hash for block %d, want %s, got %s", block.NumberU64(), block.Hash().Hex(), fb.Hash().Hex())
  1182. return
  1183. }
  1184. return
  1185. }
  1186. }(chain[i])
  1187. if _, err := blockchain.InsertChain(types.Blocks{chain[i]}); err != nil {
  1188. t.Fatalf("failed to insert block %d: %v", i, err)
  1189. }
  1190. }
  1191. pend.Wait()
  1192. }
  1193. func TestEIP155Transition(t *testing.T) {
  1194. // Configure and generate a sample block chain
  1195. var (
  1196. db = rawdb.NewMemoryDatabase()
  1197. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1198. address = crypto.PubkeyToAddress(key.PublicKey)
  1199. funds = big.NewInt(1000000000)
  1200. deleteAddr = common.Address{1}
  1201. gspec = &Genesis{
  1202. Config: &params.ChainConfig{ChainID: big.NewInt(1), EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)},
  1203. Alloc: GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}},
  1204. }
  1205. genesis = gspec.MustCommit(db)
  1206. )
  1207. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil)
  1208. defer blockchain.Stop()
  1209. blocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 4, func(i int, block *BlockGen) {
  1210. var (
  1211. tx *types.Transaction
  1212. err error
  1213. basicTx = func(signer types.Signer) (*types.Transaction, error) {
  1214. return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1215. }
  1216. )
  1217. switch i {
  1218. case 0:
  1219. tx, err = basicTx(types.HomesteadSigner{})
  1220. if err != nil {
  1221. t.Fatal(err)
  1222. }
  1223. block.AddTx(tx)
  1224. case 2:
  1225. tx, err = basicTx(types.HomesteadSigner{})
  1226. if err != nil {
  1227. t.Fatal(err)
  1228. }
  1229. block.AddTx(tx)
  1230. tx, err = basicTx(types.NewEIP155Signer(gspec.Config.ChainID))
  1231. if err != nil {
  1232. t.Fatal(err)
  1233. }
  1234. block.AddTx(tx)
  1235. case 3:
  1236. tx, err = basicTx(types.HomesteadSigner{})
  1237. if err != nil {
  1238. t.Fatal(err)
  1239. }
  1240. block.AddTx(tx)
  1241. tx, err = basicTx(types.NewEIP155Signer(gspec.Config.ChainID))
  1242. if err != nil {
  1243. t.Fatal(err)
  1244. }
  1245. block.AddTx(tx)
  1246. }
  1247. })
  1248. if _, err := blockchain.InsertChain(blocks); err != nil {
  1249. t.Fatal(err)
  1250. }
  1251. block := blockchain.GetBlockByNumber(1)
  1252. if block.Transactions()[0].Protected() {
  1253. t.Error("Expected block[0].txs[0] to not be replay protected")
  1254. }
  1255. block = blockchain.GetBlockByNumber(3)
  1256. if block.Transactions()[0].Protected() {
  1257. t.Error("Expected block[3].txs[0] to not be replay protected")
  1258. }
  1259. if !block.Transactions()[1].Protected() {
  1260. t.Error("Expected block[3].txs[1] to be replay protected")
  1261. }
  1262. if _, err := blockchain.InsertChain(blocks[4:]); err != nil {
  1263. t.Fatal(err)
  1264. }
  1265. // generate an invalid chain id transaction
  1266. config := &params.ChainConfig{ChainID: big.NewInt(2), EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)}
  1267. blocks, _ = GenerateChain(config, blocks[len(blocks)-1], ethash.NewFaker(), db, 4, func(i int, block *BlockGen) {
  1268. var (
  1269. tx *types.Transaction
  1270. err error
  1271. basicTx = func(signer types.Signer) (*types.Transaction, error) {
  1272. return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1273. }
  1274. )
  1275. if i == 0 {
  1276. tx, err = basicTx(types.NewEIP155Signer(big.NewInt(2)))
  1277. if err != nil {
  1278. t.Fatal(err)
  1279. }
  1280. block.AddTx(tx)
  1281. }
  1282. })
  1283. _, err := blockchain.InsertChain(blocks)
  1284. if err != types.ErrInvalidChainId {
  1285. t.Error("expected error:", types.ErrInvalidChainId)
  1286. }
  1287. }
  1288. func TestEIP161AccountRemoval(t *testing.T) {
  1289. // Configure and generate a sample block chain
  1290. var (
  1291. db = rawdb.NewMemoryDatabase()
  1292. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1293. address = crypto.PubkeyToAddress(key.PublicKey)
  1294. funds = big.NewInt(1000000000)
  1295. theAddr = common.Address{1}
  1296. gspec = &Genesis{
  1297. Config: &params.ChainConfig{
  1298. ChainID: big.NewInt(1),
  1299. HomesteadBlock: new(big.Int),
  1300. EIP155Block: new(big.Int),
  1301. EIP150Block: new(big.Int),
  1302. EIP158Block: big.NewInt(2),
  1303. },
  1304. Alloc: GenesisAlloc{address: {Balance: funds}},
  1305. }
  1306. genesis = gspec.MustCommit(db)
  1307. )
  1308. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil)
  1309. defer blockchain.Stop()
  1310. blocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, block *BlockGen) {
  1311. var (
  1312. tx *types.Transaction
  1313. err error
  1314. signer = types.NewEIP155Signer(gspec.Config.ChainID)
  1315. )
  1316. switch i {
  1317. case 0:
  1318. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1319. case 1:
  1320. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1321. case 2:
  1322. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1323. }
  1324. if err != nil {
  1325. t.Fatal(err)
  1326. }
  1327. block.AddTx(tx)
  1328. })
  1329. // account must exist pre eip 161
  1330. if _, err := blockchain.InsertChain(types.Blocks{blocks[0]}); err != nil {
  1331. t.Fatal(err)
  1332. }
  1333. if st, _ := blockchain.State(); !st.Exist(theAddr) {
  1334. t.Error("expected account to exist")
  1335. }
  1336. // account needs to be deleted post eip 161
  1337. if _, err := blockchain.InsertChain(types.Blocks{blocks[1]}); err != nil {
  1338. t.Fatal(err)
  1339. }
  1340. if st, _ := blockchain.State(); st.Exist(theAddr) {
  1341. t.Error("account should not exist")
  1342. }
  1343. // account musn't be created post eip 161
  1344. if _, err := blockchain.InsertChain(types.Blocks{blocks[2]}); err != nil {
  1345. t.Fatal(err)
  1346. }
  1347. if st, _ := blockchain.State(); st.Exist(theAddr) {
  1348. t.Error("account should not exist")
  1349. }
  1350. }
  1351. // This is a regression test (i.e. as weird as it is, don't delete it ever), which
  1352. // tests that under weird reorg conditions the blockchain and its internal header-
  1353. // chain return the same latest block/header.
  1354. //
  1355. // https://github.com/ethereum/go-ethereum/pull/15941
  1356. func TestBlockchainHeaderchainReorgConsistency(t *testing.T) {
  1357. // Generate a canonical chain to act as the main dataset
  1358. engine := ethash.NewFaker()
  1359. db := rawdb.NewMemoryDatabase()
  1360. genesis := new(Genesis).MustCommit(db)
  1361. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1362. // Generate a bunch of fork blocks, each side forking from the canonical chain
  1363. forks := make([]*types.Block, len(blocks))
  1364. for i := 0; i < len(forks); i++ {
  1365. parent := genesis
  1366. if i > 0 {
  1367. parent = blocks[i-1]
  1368. }
  1369. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1370. forks[i] = fork[0]
  1371. }
  1372. // Import the canonical and fork chain side by side, verifying the current block
  1373. // and current header consistency
  1374. diskdb := rawdb.NewMemoryDatabase()
  1375. new(Genesis).MustCommit(diskdb)
  1376. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
  1377. if err != nil {
  1378. t.Fatalf("failed to create tester chain: %v", err)
  1379. }
  1380. for i := 0; i < len(blocks); i++ {
  1381. if _, err := chain.InsertChain(blocks[i : i+1]); err != nil {
  1382. t.Fatalf("block %d: failed to insert into chain: %v", i, err)
  1383. }
  1384. if chain.CurrentBlock().Hash() != chain.CurrentHeader().Hash() {
  1385. 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])
  1386. }
  1387. if _, err := chain.InsertChain(forks[i : i+1]); err != nil {
  1388. t.Fatalf(" fork %d: failed to insert into chain: %v", i, err)
  1389. }
  1390. if chain.CurrentBlock().Hash() != chain.CurrentHeader().Hash() {
  1391. 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])
  1392. }
  1393. }
  1394. }
  1395. // Tests that importing small side forks doesn't leave junk in the trie database
  1396. // cache (which would eventually cause memory issues).
  1397. func TestTrieForkGC(t *testing.T) {
  1398. // Generate a canonical chain to act as the main dataset
  1399. engine := ethash.NewFaker()
  1400. db := rawdb.NewMemoryDatabase()
  1401. genesis := new(Genesis).MustCommit(db)
  1402. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2*TriesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1403. // Generate a bunch of fork blocks, each side forking from the canonical chain
  1404. forks := make([]*types.Block, len(blocks))
  1405. for i := 0; i < len(forks); i++ {
  1406. parent := genesis
  1407. if i > 0 {
  1408. parent = blocks[i-1]
  1409. }
  1410. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1411. forks[i] = fork[0]
  1412. }
  1413. // Import the canonical and fork chain side by side, forcing the trie cache to cache both
  1414. diskdb := rawdb.NewMemoryDatabase()
  1415. new(Genesis).MustCommit(diskdb)
  1416. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
  1417. if err != nil {
  1418. t.Fatalf("failed to create tester chain: %v", err)
  1419. }
  1420. for i := 0; i < len(blocks); i++ {
  1421. if _, err := chain.InsertChain(blocks[i : i+1]); err != nil {
  1422. t.Fatalf("block %d: failed to insert into chain: %v", i, err)
  1423. }
  1424. if _, err := chain.InsertChain(forks[i : i+1]); err != nil {
  1425. t.Fatalf("fork %d: failed to insert into chain: %v", i, err)
  1426. }
  1427. }
  1428. // Dereference all the recent tries and ensure no past trie is left in
  1429. for i := 0; i < TriesInMemory; i++ {
  1430. chain.stateCache.TrieDB().Dereference(blocks[len(blocks)-1-i].Root())
  1431. chain.stateCache.TrieDB().Dereference(forks[len(blocks)-1-i].Root())
  1432. }
  1433. if len(chain.stateCache.TrieDB().Nodes()) > 0 {
  1434. t.Fatalf("stale tries still alive after garbase collection")
  1435. }
  1436. }
  1437. // Tests that doing large reorgs works even if the state associated with the
  1438. // forking point is not available any more.
  1439. func TestLargeReorgTrieGC(t *testing.T) {
  1440. // Generate the original common chain segment and the two competing forks
  1441. engine := ethash.NewFaker()
  1442. db := rawdb.NewMemoryDatabase()
  1443. genesis := new(Genesis).MustCommit(db)
  1444. shared, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1445. original, _ := GenerateChain(params.TestChainConfig, shared[len(shared)-1], engine, db, 2*TriesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1446. competitor, _ := GenerateChain(params.TestChainConfig, shared[len(shared)-1], engine, db, 2*TriesInMemory+1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{3}) })
  1447. // Import the shared chain and the original canonical one
  1448. diskdb := rawdb.NewMemoryDatabase()
  1449. new(Genesis).MustCommit(diskdb)
  1450. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
  1451. if err != nil {
  1452. t.Fatalf("failed to create tester chain: %v", err)
  1453. }
  1454. if _, err := chain.InsertChain(shared); err != nil {
  1455. t.Fatalf("failed to insert shared chain: %v", err)
  1456. }
  1457. if _, err := chain.InsertChain(original); err != nil {
  1458. t.Fatalf("failed to insert original chain: %v", err)
  1459. }
  1460. // Ensure that the state associated with the forking point is pruned away
  1461. if node, _ := chain.stateCache.TrieDB().Node(shared[len(shared)-1].Root()); node != nil {
  1462. t.Fatalf("common-but-old ancestor still cache")
  1463. }
  1464. // Import the competitor chain without exceeding the canonical's TD and ensure
  1465. // we have not processed any of the blocks (protection against malicious blocks)
  1466. if _, err := chain.InsertChain(competitor[:len(competitor)-2]); err != nil {
  1467. t.Fatalf("failed to insert competitor chain: %v", err)
  1468. }
  1469. for i, block := range competitor[:len(competitor)-2] {
  1470. if node, _ := chain.stateCache.TrieDB().Node(block.Root()); node != nil {
  1471. t.Fatalf("competitor %d: low TD chain became processed", i)
  1472. }
  1473. }
  1474. // Import the head of the competitor chain, triggering the reorg and ensure we
  1475. // successfully reprocess all the stashed away blocks.
  1476. if _, err := chain.InsertChain(competitor[len(competitor)-2:]); err != nil {
  1477. t.Fatalf("failed to finalize competitor chain: %v", err)
  1478. }
  1479. for i, block := range competitor[:len(competitor)-TriesInMemory] {
  1480. if node, _ := chain.stateCache.TrieDB().Node(block.Root()); node != nil {
  1481. t.Fatalf("competitor %d: competing chain state missing", i)
  1482. }
  1483. }
  1484. }
  1485. func TestBlockchainRecovery(t *testing.T) {
  1486. // Configure and generate a sample block chain
  1487. var (
  1488. gendb = rawdb.NewMemoryDatabase()
  1489. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1490. address = crypto.PubkeyToAddress(key.PublicKey)
  1491. funds = big.NewInt(1000000000)
  1492. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{address: {Balance: funds}}}
  1493. genesis = gspec.MustCommit(gendb)
  1494. )
  1495. height := uint64(1024)
  1496. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil)
  1497. // Import the chain as a ancient-first node and ensure all pointers are updated
  1498. frdir, err := ioutil.TempDir("", "")
  1499. if err != nil {
  1500. t.Fatalf("failed to create temp freezer dir: %v", err)
  1501. }
  1502. defer os.Remove(frdir)
  1503. ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "")
  1504. if err != nil {
  1505. t.Fatalf("failed to create temp freezer db: %v", err)
  1506. }
  1507. gspec.MustCommit(ancientDb)
  1508. ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil)
  1509. headers := make([]*types.Header, len(blocks))
  1510. for i, block := range blocks {
  1511. headers[i] = block.Header()
  1512. }
  1513. if n, err := ancient.InsertHeaderChain(headers, 1); err != nil {
  1514. t.Fatalf("failed to insert header %d: %v", n, err)
  1515. }
  1516. if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err != nil {
  1517. t.Fatalf("failed to insert receipt %d: %v", n, err)
  1518. }
  1519. ancient.Stop()
  1520. // Destroy head fast block manually
  1521. midBlock := blocks[len(blocks)/2]
  1522. rawdb.WriteHeadFastBlockHash(ancientDb, midBlock.Hash())
  1523. // Reopen broken blockchain again
  1524. ancient, _ = NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil)
  1525. defer ancient.Stop()
  1526. if num := ancient.CurrentBlock().NumberU64(); num != 0 {
  1527. t.Errorf("head block mismatch: have #%v, want #%v", num, 0)
  1528. }
  1529. if num := ancient.CurrentFastBlock().NumberU64(); num != midBlock.NumberU64() {
  1530. t.Errorf("head fast-block mismatch: have #%v, want #%v", num, midBlock.NumberU64())
  1531. }
  1532. if num := ancient.CurrentHeader().Number.Uint64(); num != midBlock.NumberU64() {
  1533. t.Errorf("head header mismatch: have #%v, want #%v", num, midBlock.NumberU64())
  1534. }
  1535. }
  1536. func TestIncompleteAncientReceiptChainInsertion(t *testing.T) {
  1537. // Configure and generate a sample block chain
  1538. var (
  1539. gendb = rawdb.NewMemoryDatabase()
  1540. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1541. address = crypto.PubkeyToAddress(key.PublicKey)
  1542. funds = big.NewInt(1000000000)
  1543. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{address: {Balance: funds}}}
  1544. genesis = gspec.MustCommit(gendb)
  1545. )
  1546. height := uint64(1024)
  1547. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil)
  1548. // Import the chain as a ancient-first node and ensure all pointers are updated
  1549. frdir, err := ioutil.TempDir("", "")
  1550. if err != nil {
  1551. t.Fatalf("failed to create temp freezer dir: %v", err)
  1552. }
  1553. defer os.Remove(frdir)
  1554. ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "")
  1555. if err != nil {
  1556. t.Fatalf("failed to create temp freezer db: %v", err)
  1557. }
  1558. gspec.MustCommit(ancientDb)
  1559. ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil)
  1560. defer ancient.Stop()
  1561. headers := make([]*types.Header, len(blocks))
  1562. for i, block := range blocks {
  1563. headers[i] = block.Header()
  1564. }
  1565. if n, err := ancient.InsertHeaderChain(headers, 1); err != nil {
  1566. t.Fatalf("failed to insert header %d: %v", n, err)
  1567. }
  1568. // Abort ancient receipt chain insertion deliberately
  1569. ancient.terminateInsert = func(hash common.Hash, number uint64) bool {
  1570. return number == blocks[len(blocks)/2].NumberU64()
  1571. }
  1572. previousFastBlock := ancient.CurrentFastBlock()
  1573. if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err == nil {
  1574. t.Fatalf("failed to insert receipt %d: %v", n, err)
  1575. }
  1576. if ancient.CurrentFastBlock().NumberU64() != previousFastBlock.NumberU64() {
  1577. t.Fatalf("failed to rollback ancient data, want %d, have %d", previousFastBlock.NumberU64(), ancient.CurrentFastBlock().NumberU64())
  1578. }
  1579. if frozen, err := ancient.db.Ancients(); err != nil || frozen != 1 {
  1580. t.Fatalf("failed to truncate ancient data")
  1581. }
  1582. ancient.terminateInsert = nil
  1583. if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err != nil {
  1584. t.Fatalf("failed to insert receipt %d: %v", n, err)
  1585. }
  1586. if ancient.CurrentFastBlock().NumberU64() != blocks[len(blocks)-1].NumberU64() {
  1587. t.Fatalf("failed to insert ancient recept chain after rollback")
  1588. }
  1589. }
  1590. // Tests that importing a very large side fork, which is larger than the canon chain,
  1591. // but where the difficulty per block is kept low: this means that it will not
  1592. // overtake the 'canon' chain until after it's passed canon by about 200 blocks.
  1593. //
  1594. // Details at:
  1595. // - https://github.com/ethereum/go-ethereum/issues/18977
  1596. // - https://github.com/ethereum/go-ethereum/pull/18988
  1597. func TestLowDiffLongChain(t *testing.T) {
  1598. // Generate a canonical chain to act as the main dataset
  1599. engine := ethash.NewFaker()
  1600. db := rawdb.NewMemoryDatabase()
  1601. genesis := new(Genesis).MustCommit(db)
  1602. // We must use a pretty long chain to ensure that the fork doesn't overtake us
  1603. // until after at least 128 blocks post tip
  1604. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 6*TriesInMemory, func(i int, b *BlockGen) {
  1605. b.SetCoinbase(common.Address{1})
  1606. b.OffsetTime(-9)
  1607. })
  1608. // Import the canonical chain
  1609. diskdb := rawdb.NewMemoryDatabase()
  1610. new(Genesis).MustCommit(diskdb)
  1611. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
  1612. if err != nil {
  1613. t.Fatalf("failed to create tester chain: %v", err)
  1614. }
  1615. if n, err := chain.InsertChain(blocks); err != nil {
  1616. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  1617. }
  1618. // Generate fork chain, starting from an early block
  1619. parent := blocks[10]
  1620. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 8*TriesInMemory, func(i int, b *BlockGen) {
  1621. b.SetCoinbase(common.Address{2})
  1622. })
  1623. // And now import the fork
  1624. if i, err := chain.InsertChain(fork); err != nil {
  1625. t.Fatalf("block %d: failed to insert into chain: %v", i, err)
  1626. }
  1627. head := chain.CurrentBlock()
  1628. if got := fork[len(fork)-1].Hash(); got != head.Hash() {
  1629. t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
  1630. }
  1631. // Sanity check that all the canonical numbers are present
  1632. header := chain.CurrentHeader()
  1633. for number := head.NumberU64(); number > 0; number-- {
  1634. if hash := chain.GetHeaderByNumber(number).Hash(); hash != header.Hash() {
  1635. t.Fatalf("header %d: canonical hash mismatch: have %x, want %x", number, hash, header.Hash())
  1636. }
  1637. header = chain.GetHeader(header.ParentHash, number-1)
  1638. }
  1639. }
  1640. // Tests that importing a sidechain (S), where
  1641. // - S is sidechain, containing blocks [Sn...Sm]
  1642. // - C is canon chain, containing blocks [G..Cn..Cm]
  1643. // - A common ancestor is placed at prune-point + blocksBetweenCommonAncestorAndPruneblock
  1644. // - The sidechain S is prepended with numCanonBlocksInSidechain blocks from the canon chain
  1645. func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommonAncestorAndPruneblock int) {
  1646. // Generate a canonical chain to act as the main dataset
  1647. engine := ethash.NewFaker()
  1648. db := rawdb.NewMemoryDatabase()
  1649. genesis := new(Genesis).MustCommit(db)
  1650. // Generate and import the canonical chain
  1651. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2*TriesInMemory, nil)
  1652. diskdb := rawdb.NewMemoryDatabase()
  1653. new(Genesis).MustCommit(diskdb)
  1654. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
  1655. if err != nil {
  1656. t.Fatalf("failed to create tester chain: %v", err)
  1657. }
  1658. if n, err := chain.InsertChain(blocks); err != nil {
  1659. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  1660. }
  1661. lastPrunedIndex := len(blocks) - TriesInMemory - 1
  1662. lastPrunedBlock := blocks[lastPrunedIndex]
  1663. firstNonPrunedBlock := blocks[len(blocks)-TriesInMemory]
  1664. // Verify pruning of lastPrunedBlock
  1665. if chain.HasBlockAndState(lastPrunedBlock.Hash(), lastPrunedBlock.NumberU64()) {
  1666. t.Errorf("Block %d not pruned", lastPrunedBlock.NumberU64())
  1667. }
  1668. // Verify firstNonPrunedBlock is not pruned
  1669. if !chain.HasBlockAndState(firstNonPrunedBlock.Hash(), firstNonPrunedBlock.NumberU64()) {
  1670. t.Errorf("Block %d pruned", firstNonPrunedBlock.NumberU64())
  1671. }
  1672. // Generate the sidechain
  1673. // First block should be a known block, block after should be a pruned block. So
  1674. // canon(pruned), side, side...
  1675. // Generate fork chain, make it longer than canon
  1676. parentIndex := lastPrunedIndex + blocksBetweenCommonAncestorAndPruneblock
  1677. parent := blocks[parentIndex]
  1678. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 2*TriesInMemory, func(i int, b *BlockGen) {
  1679. b.SetCoinbase(common.Address{2})
  1680. })
  1681. // Prepend the parent(s)
  1682. var sidechain []*types.Block
  1683. for i := numCanonBlocksInSidechain; i > 0; i-- {
  1684. sidechain = append(sidechain, blocks[parentIndex+1-i])
  1685. }
  1686. sidechain = append(sidechain, fork...)
  1687. _, err = chain.InsertChain(sidechain)
  1688. if err != nil {
  1689. t.Errorf("Got error, %v", err)
  1690. }
  1691. head := chain.CurrentBlock()
  1692. if got := fork[len(fork)-1].Hash(); got != head.Hash() {
  1693. t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
  1694. }
  1695. }
  1696. // Tests that importing a sidechain (S), where
  1697. // - S is sidechain, containing blocks [Sn...Sm]
  1698. // - C is canon chain, containing blocks [G..Cn..Cm]
  1699. // - The common ancestor Cc is pruned
  1700. // - The first block in S: Sn, is == Cn
  1701. // That is: the sidechain for import contains some blocks already present in canon chain.
  1702. // So the blocks are
  1703. // [ Cn, Cn+1, Cc, Sn+3 ... Sm]
  1704. // ^ ^ ^ pruned
  1705. func TestPrunedImportSide(t *testing.T) {
  1706. //glogger := log.NewGlogHandler(log.StreamHandler(os.Stdout, log.TerminalFormat(false)))
  1707. //glogger.Verbosity(3)
  1708. //log.Root().SetHandler(log.Handler(glogger))
  1709. testSideImport(t, 3, 3)
  1710. testSideImport(t, 3, -3)
  1711. testSideImport(t, 10, 0)
  1712. testSideImport(t, 1, 10)
  1713. testSideImport(t, 1, -10)
  1714. }
  1715. func TestInsertKnownHeaders(t *testing.T) { testInsertKnownChainData(t, "headers") }
  1716. func TestInsertKnownReceiptChain(t *testing.T) { testInsertKnownChainData(t, "receipts") }
  1717. func TestInsertKnownBlocks(t *testing.T) { testInsertKnownChainData(t, "blocks") }
  1718. func testInsertKnownChainData(t *testing.T, typ string) {
  1719. engine := ethash.NewFaker()
  1720. db := rawdb.NewMemoryDatabase()
  1721. genesis := new(Genesis).MustCommit(db)
  1722. blocks, receipts := GenerateChain(params.TestChainConfig, genesis, engine, db, 32, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1723. // A longer chain but total difficulty is lower.
  1724. blocks2, receipts2 := GenerateChain(params.TestChainConfig, blocks[len(blocks)-1], engine, db, 65, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1725. // A shorter chain but total difficulty is higher.
  1726. blocks3, receipts3 := GenerateChain(params.TestChainConfig, blocks[len(blocks)-1], engine, db, 64, func(i int, b *BlockGen) {
  1727. b.SetCoinbase(common.Address{1})
  1728. b.OffsetTime(-9) // A higher difficulty
  1729. })
  1730. // Import the shared chain and the original canonical one
  1731. dir, err := ioutil.TempDir("", "")
  1732. if err != nil {
  1733. t.Fatalf("failed to create temp freezer dir: %v", err)
  1734. }
  1735. defer os.Remove(dir)
  1736. chaindb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), dir, "")
  1737. if err != nil {
  1738. t.Fatalf("failed to create temp freezer db: %v", err)
  1739. }
  1740. new(Genesis).MustCommit(chaindb)
  1741. defer os.RemoveAll(dir)
  1742. chain, err := NewBlockChain(chaindb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
  1743. if err != nil {
  1744. t.Fatalf("failed to create tester chain: %v", err)
  1745. }
  1746. var (
  1747. inserter func(blocks []*types.Block, receipts []types.Receipts) error
  1748. asserter func(t *testing.T, block *types.Block)
  1749. )
  1750. if typ == "headers" {
  1751. inserter = func(blocks []*types.Block, receipts []types.Receipts) error {
  1752. headers := make([]*types.Header, 0, len(blocks))
  1753. for _, block := range blocks {
  1754. headers = append(headers, block.Header())
  1755. }
  1756. _, err := chain.InsertHeaderChain(headers, 1)
  1757. return err
  1758. }
  1759. asserter = func(t *testing.T, block *types.Block) {
  1760. if chain.CurrentHeader().Hash() != block.Hash() {
  1761. t.Fatalf("current head header mismatch, have %v, want %v", chain.CurrentHeader().Hash().Hex(), block.Hash().Hex())
  1762. }
  1763. }
  1764. } else if typ == "receipts" {
  1765. inserter = func(blocks []*types.Block, receipts []types.Receipts) error {
  1766. headers := make([]*types.Header, 0, len(blocks))
  1767. for _, block := range blocks {
  1768. headers = append(headers, block.Header())
  1769. }
  1770. _, err := chain.InsertHeaderChain(headers, 1)
  1771. if err != nil {
  1772. return err
  1773. }
  1774. _, err = chain.InsertReceiptChain(blocks, receipts, 0)
  1775. return err
  1776. }
  1777. asserter = func(t *testing.T, block *types.Block) {
  1778. if chain.CurrentFastBlock().Hash() != block.Hash() {
  1779. t.Fatalf("current head fast block mismatch, have %v, want %v", chain.CurrentFastBlock().Hash().Hex(), block.Hash().Hex())
  1780. }
  1781. }
  1782. } else {
  1783. inserter = func(blocks []*types.Block, receipts []types.Receipts) error {
  1784. _, err := chain.InsertChain(blocks)
  1785. return err
  1786. }
  1787. asserter = func(t *testing.T, block *types.Block) {
  1788. if chain.CurrentBlock().Hash() != block.Hash() {
  1789. t.Fatalf("current head block mismatch, have %v, want %v", chain.CurrentBlock().Hash().Hex(), block.Hash().Hex())
  1790. }
  1791. }
  1792. }
  1793. if err := inserter(blocks, receipts); err != nil {
  1794. t.Fatalf("failed to insert chain data: %v", err)
  1795. }
  1796. // Reimport the chain data again. All the imported
  1797. // chain data are regarded "known" data.
  1798. if err := inserter(blocks, receipts); err != nil {
  1799. t.Fatalf("failed to insert chain data: %v", err)
  1800. }
  1801. asserter(t, blocks[len(blocks)-1])
  1802. // Import a long canonical chain with some known data as prefix.
  1803. var rollback []common.Hash
  1804. for i := len(blocks) / 2; i < len(blocks); i++ {
  1805. rollback = append(rollback, blocks[i].Hash())
  1806. }
  1807. chain.Rollback(rollback)
  1808. if err := inserter(append(blocks, blocks2...), append(receipts, receipts2...)); err != nil {
  1809. t.Fatalf("failed to insert chain data: %v", err)
  1810. }
  1811. asserter(t, blocks2[len(blocks2)-1])
  1812. // Import a heavier shorter but higher total difficulty chain with some known data as prefix.
  1813. if err := inserter(append(blocks, blocks3...), append(receipts, receipts3...)); err != nil {
  1814. t.Fatalf("failed to insert chain data: %v", err)
  1815. }
  1816. asserter(t, blocks3[len(blocks3)-1])
  1817. // Import a longer but lower total difficulty chain with some known data as prefix.
  1818. if err := inserter(append(blocks, blocks2...), append(receipts, receipts2...)); err != nil {
  1819. t.Fatalf("failed to insert chain data: %v", err)
  1820. }
  1821. // The head shouldn't change.
  1822. asserter(t, blocks3[len(blocks3)-1])
  1823. // Rollback the heavier chain and re-insert the longer chain again
  1824. for i := 0; i < len(blocks3); i++ {
  1825. rollback = append(rollback, blocks3[i].Hash())
  1826. }
  1827. chain.Rollback(rollback)
  1828. if err := inserter(append(blocks, blocks2...), append(receipts, receipts2...)); err != nil {
  1829. t.Fatalf("failed to insert chain data: %v", err)
  1830. }
  1831. asserter(t, blocks2[len(blocks2)-1])
  1832. }
  1833. // getLongAndShortChains returns two chains,
  1834. // A is longer, B is heavier
  1835. func getLongAndShortChains() (*BlockChain, []*types.Block, []*types.Block, error) {
  1836. // Generate a canonical chain to act as the main dataset
  1837. engine := ethash.NewFaker()
  1838. db := rawdb.NewMemoryDatabase()
  1839. genesis := new(Genesis).MustCommit(db)
  1840. // Generate and import the canonical chain,
  1841. // Offset the time, to keep the difficulty low
  1842. longChain, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 80, func(i int, b *BlockGen) {
  1843. b.SetCoinbase(common.Address{1})
  1844. })
  1845. diskdb := rawdb.NewMemoryDatabase()
  1846. new(Genesis).MustCommit(diskdb)
  1847. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
  1848. if err != nil {
  1849. return nil, nil, nil, fmt.Errorf("failed to create tester chain: %v", err)
  1850. }
  1851. // Generate fork chain, make it shorter than canon, with common ancestor pretty early
  1852. parentIndex := 3
  1853. parent := longChain[parentIndex]
  1854. heavyChain, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 75, func(i int, b *BlockGen) {
  1855. b.SetCoinbase(common.Address{2})
  1856. b.OffsetTime(-9)
  1857. })
  1858. // Verify that the test is sane
  1859. var (
  1860. longerTd = new(big.Int)
  1861. shorterTd = new(big.Int)
  1862. )
  1863. for index, b := range longChain {
  1864. longerTd.Add(longerTd, b.Difficulty())
  1865. if index <= parentIndex {
  1866. shorterTd.Add(shorterTd, b.Difficulty())
  1867. }
  1868. }
  1869. for _, b := range heavyChain {
  1870. shorterTd.Add(shorterTd, b.Difficulty())
  1871. }
  1872. if shorterTd.Cmp(longerTd) <= 0 {
  1873. return nil, nil, nil, fmt.Errorf("Test is moot, heavyChain td (%v) must be larger than canon td (%v)", shorterTd, longerTd)
  1874. }
  1875. longerNum := longChain[len(longChain)-1].NumberU64()
  1876. shorterNum := heavyChain[len(heavyChain)-1].NumberU64()
  1877. if shorterNum >= longerNum {
  1878. return nil, nil, nil, fmt.Errorf("Test is moot, heavyChain num (%v) must be lower than canon num (%v)", shorterNum, longerNum)
  1879. }
  1880. return chain, longChain, heavyChain, nil
  1881. }
  1882. // TestReorgToShorterRemovesCanonMapping tests that if we
  1883. // 1. Have a chain [0 ... N .. X]
  1884. // 2. Reorg to shorter but heavier chain [0 ... N ... Y]
  1885. // 3. Then there should be no canon mapping for the block at height X
  1886. func TestReorgToShorterRemovesCanonMapping(t *testing.T) {
  1887. chain, canonblocks, sideblocks, err := getLongAndShortChains()
  1888. if err != nil {
  1889. t.Fatal(err)
  1890. }
  1891. if n, err := chain.InsertChain(canonblocks); err != nil {
  1892. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  1893. }
  1894. canonNum := chain.CurrentBlock().NumberU64()
  1895. _, err = chain.InsertChain(sideblocks)
  1896. if err != nil {
  1897. t.Errorf("Got error, %v", err)
  1898. }
  1899. head := chain.CurrentBlock()
  1900. if got := sideblocks[len(sideblocks)-1].Hash(); got != head.Hash() {
  1901. t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
  1902. }
  1903. // We have now inserted a sidechain.
  1904. if blockByNum := chain.GetBlockByNumber(canonNum); blockByNum != nil {
  1905. t.Errorf("expected block to be gone: %v", blockByNum.NumberU64())
  1906. }
  1907. if headerByNum := chain.GetHeaderByNumber(canonNum); headerByNum != nil {
  1908. t.Errorf("expected header to be gone: %v", headerByNum.Number.Uint64())
  1909. }
  1910. }
  1911. // TestReorgToShorterRemovesCanonMappingHeaderChain is the same scenario
  1912. // as TestReorgToShorterRemovesCanonMapping, but applied on headerchain
  1913. // imports -- that is, for fast sync
  1914. func TestReorgToShorterRemovesCanonMappingHeaderChain(t *testing.T) {
  1915. chain, canonblocks, sideblocks, err := getLongAndShortChains()
  1916. if err != nil {
  1917. t.Fatal(err)
  1918. }
  1919. // Convert into headers
  1920. canonHeaders := make([]*types.Header, len(canonblocks))
  1921. for i, block := range canonblocks {
  1922. canonHeaders[i] = block.Header()
  1923. }
  1924. if n, err := chain.InsertHeaderChain(canonHeaders, 0); err != nil {
  1925. t.Fatalf("header %d: failed to insert into chain: %v", n, err)
  1926. }
  1927. canonNum := chain.CurrentHeader().Number.Uint64()
  1928. sideHeaders := make([]*types.Header, len(sideblocks))
  1929. for i, block := range sideblocks {
  1930. sideHeaders[i] = block.Header()
  1931. }
  1932. if n, err := chain.InsertHeaderChain(sideHeaders, 0); err != nil {
  1933. t.Fatalf("header %d: failed to insert into chain: %v", n, err)
  1934. }
  1935. head := chain.CurrentHeader()
  1936. if got := sideblocks[len(sideblocks)-1].Hash(); got != head.Hash() {
  1937. t.Fatalf("head wrong, expected %x got %x", head.Hash(), got)
  1938. }
  1939. // We have now inserted a sidechain.
  1940. if blockByNum := chain.GetBlockByNumber(canonNum); blockByNum != nil {
  1941. t.Errorf("expected block to be gone: %v", blockByNum.NumberU64())
  1942. }
  1943. if headerByNum := chain.GetHeaderByNumber(canonNum); headerByNum != nil {
  1944. t.Errorf("expected header to be gone: %v", headerByNum.Number.Uint64())
  1945. }
  1946. }
  1947. // Benchmarks large blocks with value transfers to non-existing accounts
  1948. func benchmarkLargeNumberOfValueToNonexisting(b *testing.B, numTxs, numBlocks int, recipientFn func(uint64) common.Address, dataFn func(uint64) []byte) {
  1949. var (
  1950. signer = types.HomesteadSigner{}
  1951. testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1952. testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
  1953. bankFunds = big.NewInt(100000000000000000)
  1954. gspec = Genesis{
  1955. Config: params.TestChainConfig,
  1956. Alloc: GenesisAlloc{
  1957. testBankAddress: {Balance: bankFunds},
  1958. common.HexToAddress("0xc0de"): {
  1959. Code: []byte{0x60, 0x01, 0x50},
  1960. Balance: big.NewInt(0),
  1961. }, // push 1, pop
  1962. },
  1963. GasLimit: 100e6, // 100 M
  1964. }
  1965. )
  1966. // Generate the original common chain segment and the two competing forks
  1967. engine := ethash.NewFaker()
  1968. db := rawdb.NewMemoryDatabase()
  1969. genesis := gspec.MustCommit(db)
  1970. blockGenerator := func(i int, block *BlockGen) {
  1971. block.SetCoinbase(common.Address{1})
  1972. for txi := 0; txi < numTxs; txi++ {
  1973. uniq := uint64(i*numTxs + txi)
  1974. recipient := recipientFn(uniq)
  1975. tx, err := types.SignTx(types.NewTransaction(uniq, recipient, big.NewInt(1), params.TxGas, big.NewInt(1), nil), signer, testBankKey)
  1976. if err != nil {
  1977. b.Error(err)
  1978. }
  1979. block.AddTx(tx)
  1980. }
  1981. }
  1982. shared, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, numBlocks, blockGenerator)
  1983. b.StopTimer()
  1984. b.ResetTimer()
  1985. for i := 0; i < b.N; i++ {
  1986. // Import the shared chain and the original canonical one
  1987. diskdb := rawdb.NewMemoryDatabase()
  1988. gspec.MustCommit(diskdb)
  1989. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
  1990. if err != nil {
  1991. b.Fatalf("failed to create tester chain: %v", err)
  1992. }
  1993. b.StartTimer()
  1994. if _, err := chain.InsertChain(shared); err != nil {
  1995. b.Fatalf("failed to insert shared chain: %v", err)
  1996. }
  1997. b.StopTimer()
  1998. if got := chain.CurrentBlock().Transactions().Len(); got != numTxs*numBlocks {
  1999. b.Fatalf("Transactions were not included, expected %d, got %d", numTxs*numBlocks, got)
  2000. }
  2001. }
  2002. }
  2003. func BenchmarkBlockChain_1x1000ValueTransferToNonexisting(b *testing.B) {
  2004. var (
  2005. numTxs = 1000
  2006. numBlocks = 1
  2007. )
  2008. recipientFn := func(nonce uint64) common.Address {
  2009. return common.BigToAddress(big.NewInt(0).SetUint64(1337 + nonce))
  2010. }
  2011. dataFn := func(nonce uint64) []byte {
  2012. return nil
  2013. }
  2014. benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn)
  2015. }
  2016. func BenchmarkBlockChain_1x1000ValueTransferToExisting(b *testing.B) {
  2017. var (
  2018. numTxs = 1000
  2019. numBlocks = 1
  2020. )
  2021. b.StopTimer()
  2022. b.ResetTimer()
  2023. recipientFn := func(nonce uint64) common.Address {
  2024. return common.BigToAddress(big.NewInt(0).SetUint64(1337))
  2025. }
  2026. dataFn := func(nonce uint64) []byte {
  2027. return nil
  2028. }
  2029. benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn)
  2030. }
  2031. func BenchmarkBlockChain_1x1000Executions(b *testing.B) {
  2032. var (
  2033. numTxs = 1000
  2034. numBlocks = 1
  2035. )
  2036. b.StopTimer()
  2037. b.ResetTimer()
  2038. recipientFn := func(nonce uint64) common.Address {
  2039. return common.BigToAddress(big.NewInt(0).SetUint64(0xc0de))
  2040. }
  2041. dataFn := func(nonce uint64) []byte {
  2042. return nil
  2043. }
  2044. benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn)
  2045. }
  2046. // Tests that importing a some old blocks, where all blocks are before the
  2047. // pruning point.
  2048. // This internally leads to a sidechain import, since the blocks trigger an
  2049. // ErrPrunedAncestor error.
  2050. // This may e.g. happen if
  2051. // 1. Downloader rollbacks a batch of inserted blocks and exits
  2052. // 2. Downloader starts to sync again
  2053. // 3. The blocks fetched are all known and canonical blocks
  2054. func TestSideImportPrunedBlocks(t *testing.T) {
  2055. // Generate a canonical chain to act as the main dataset
  2056. engine := ethash.NewFaker()
  2057. db := rawdb.NewMemoryDatabase()
  2058. genesis := new(Genesis).MustCommit(db)
  2059. // Generate and import the canonical chain
  2060. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2*TriesInMemory, nil)
  2061. diskdb := rawdb.NewMemoryDatabase()
  2062. new(Genesis).MustCommit(diskdb)
  2063. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
  2064. if err != nil {
  2065. t.Fatalf("failed to create tester chain: %v", err)
  2066. }
  2067. if n, err := chain.InsertChain(blocks); err != nil {
  2068. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2069. }
  2070. lastPrunedIndex := len(blocks) - TriesInMemory - 1
  2071. lastPrunedBlock := blocks[lastPrunedIndex]
  2072. // Verify pruning of lastPrunedBlock
  2073. if chain.HasBlockAndState(lastPrunedBlock.Hash(), lastPrunedBlock.NumberU64()) {
  2074. t.Errorf("Block %d not pruned", lastPrunedBlock.NumberU64())
  2075. }
  2076. firstNonPrunedBlock := blocks[len(blocks)-TriesInMemory]
  2077. // Verify firstNonPrunedBlock is not pruned
  2078. if !chain.HasBlockAndState(firstNonPrunedBlock.Hash(), firstNonPrunedBlock.NumberU64()) {
  2079. t.Errorf("Block %d pruned", firstNonPrunedBlock.NumberU64())
  2080. }
  2081. // Now re-import some old blocks
  2082. blockToReimport := blocks[5:8]
  2083. _, err = chain.InsertChain(blockToReimport)
  2084. if err != nil {
  2085. t.Errorf("Got error, %v", err)
  2086. }
  2087. }
  2088. // TestDeleteCreateRevert tests a weird state transition corner case that we hit
  2089. // while changing the internals of statedb. The workflow is that a contract is
  2090. // self destructed, then in a followup transaction (but same block) it's created
  2091. // again and the transaction reverted.
  2092. //
  2093. // The original statedb implementation flushed dirty objects to the tries after
  2094. // each transaction, so this works ok. The rework accumulated writes in memory
  2095. // first, but the journal wiped the entire state object on create-revert.
  2096. func TestDeleteCreateRevert(t *testing.T) {
  2097. var (
  2098. aa = common.HexToAddress("0x000000000000000000000000000000000000aaaa")
  2099. bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
  2100. // Generate a canonical chain to act as the main dataset
  2101. engine = ethash.NewFaker()
  2102. db = rawdb.NewMemoryDatabase()
  2103. // A sender who makes transactions, has some funds
  2104. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2105. address = crypto.PubkeyToAddress(key.PublicKey)
  2106. funds = big.NewInt(1000000000)
  2107. gspec = &Genesis{
  2108. Config: params.TestChainConfig,
  2109. Alloc: GenesisAlloc{
  2110. address: {Balance: funds},
  2111. // The address 0xAAAAA selfdestructs if called
  2112. aa: {
  2113. // Code needs to just selfdestruct
  2114. Code: []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)},
  2115. Nonce: 1,
  2116. Balance: big.NewInt(0),
  2117. },
  2118. // The address 0xBBBB send 1 wei to 0xAAAA, then reverts
  2119. bb: {
  2120. Code: []byte{
  2121. byte(vm.PC), // [0]
  2122. byte(vm.DUP1), // [0,0]
  2123. byte(vm.DUP1), // [0,0,0]
  2124. byte(vm.DUP1), // [0,0,0,0]
  2125. byte(vm.PUSH1), 0x01, // [0,0,0,0,1] (value)
  2126. byte(vm.PUSH2), 0xaa, 0xaa, // [0,0,0,0,1, 0xaaaa]
  2127. byte(vm.GAS),
  2128. byte(vm.CALL),
  2129. byte(vm.REVERT),
  2130. },
  2131. Balance: big.NewInt(1),
  2132. },
  2133. },
  2134. }
  2135. genesis = gspec.MustCommit(db)
  2136. )
  2137. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 1, func(i int, b *BlockGen) {
  2138. b.SetCoinbase(common.Address{1})
  2139. // One transaction to AAAA
  2140. tx, _ := types.SignTx(types.NewTransaction(0, aa,
  2141. big.NewInt(0), 50000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2142. b.AddTx(tx)
  2143. // One transaction to BBBB
  2144. tx, _ = types.SignTx(types.NewTransaction(1, bb,
  2145. big.NewInt(0), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2146. b.AddTx(tx)
  2147. })
  2148. // Import the canonical chain
  2149. diskdb := rawdb.NewMemoryDatabase()
  2150. gspec.MustCommit(diskdb)
  2151. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{}, nil)
  2152. if err != nil {
  2153. t.Fatalf("failed to create tester chain: %v", err)
  2154. }
  2155. if n, err := chain.InsertChain(blocks); err != nil {
  2156. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2157. }
  2158. }
  2159. // TestDeleteRecreateSlots tests a state-transition that contains both deletion
  2160. // and recreation of contract state.
  2161. // Contract A exists, has slots 1 and 2 set
  2162. // Tx 1: Selfdestruct A
  2163. // Tx 2: Re-create A, set slots 3 and 4
  2164. // Expected outcome is that _all_ slots are cleared from A, due to the selfdestruct,
  2165. // and then the new slots exist
  2166. func TestDeleteRecreateSlots(t *testing.T) {
  2167. var (
  2168. // Generate a canonical chain to act as the main dataset
  2169. engine = ethash.NewFaker()
  2170. db = rawdb.NewMemoryDatabase()
  2171. // A sender who makes transactions, has some funds
  2172. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2173. address = crypto.PubkeyToAddress(key.PublicKey)
  2174. funds = big.NewInt(1000000000)
  2175. bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
  2176. aaStorage = make(map[common.Hash]common.Hash) // Initial storage in AA
  2177. aaCode = []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)} // Code for AA (simple selfdestruct)
  2178. )
  2179. // Populate two slots
  2180. aaStorage[common.HexToHash("01")] = common.HexToHash("01")
  2181. aaStorage[common.HexToHash("02")] = common.HexToHash("02")
  2182. // The bb-code needs to CREATE2 the aa contract. It consists of
  2183. // both initcode and deployment code
  2184. // initcode:
  2185. // 1. Set slots 3=3, 4=4,
  2186. // 2. Return aaCode
  2187. initCode := []byte{
  2188. byte(vm.PUSH1), 0x3, // value
  2189. byte(vm.PUSH1), 0x3, // location
  2190. byte(vm.SSTORE), // Set slot[3] = 1
  2191. byte(vm.PUSH1), 0x4, // value
  2192. byte(vm.PUSH1), 0x4, // location
  2193. byte(vm.SSTORE), // Set slot[4] = 1
  2194. // Slots are set, now return the code
  2195. byte(vm.PUSH2), byte(vm.PC), byte(vm.SELFDESTRUCT), // Push code on stack
  2196. byte(vm.PUSH1), 0x0, // memory start on stack
  2197. byte(vm.MSTORE),
  2198. // Code is now in memory.
  2199. byte(vm.PUSH1), 0x2, // size
  2200. byte(vm.PUSH1), byte(32 - 2), // offset
  2201. byte(vm.RETURN),
  2202. }
  2203. if l := len(initCode); l > 32 {
  2204. t.Fatalf("init code is too long for a pushx, need a more elaborate deployer")
  2205. }
  2206. bbCode := []byte{
  2207. // Push initcode onto stack
  2208. byte(vm.PUSH1) + byte(len(initCode)-1)}
  2209. bbCode = append(bbCode, initCode...)
  2210. bbCode = append(bbCode, []byte{
  2211. byte(vm.PUSH1), 0x0, // memory start on stack
  2212. byte(vm.MSTORE),
  2213. byte(vm.PUSH1), 0x00, // salt
  2214. byte(vm.PUSH1), byte(len(initCode)), // size
  2215. byte(vm.PUSH1), byte(32 - len(initCode)), // offset
  2216. byte(vm.PUSH1), 0x00, // endowment
  2217. byte(vm.CREATE2),
  2218. }...)
  2219. initHash := crypto.Keccak256Hash(initCode)
  2220. aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:])
  2221. t.Logf("Destination address: %x\n", aa)
  2222. gspec := &Genesis{
  2223. Config: params.TestChainConfig,
  2224. Alloc: GenesisAlloc{
  2225. address: {Balance: funds},
  2226. // The address 0xAAAAA selfdestructs if called
  2227. aa: {
  2228. // Code needs to just selfdestruct
  2229. Code: aaCode,
  2230. Nonce: 1,
  2231. Balance: big.NewInt(0),
  2232. Storage: aaStorage,
  2233. },
  2234. // The contract BB recreates AA
  2235. bb: {
  2236. Code: bbCode,
  2237. Balance: big.NewInt(1),
  2238. },
  2239. },
  2240. }
  2241. genesis := gspec.MustCommit(db)
  2242. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 1, func(i int, b *BlockGen) {
  2243. b.SetCoinbase(common.Address{1})
  2244. // One transaction to AA, to kill it
  2245. tx, _ := types.SignTx(types.NewTransaction(0, aa,
  2246. big.NewInt(0), 50000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2247. b.AddTx(tx)
  2248. // One transaction to BB, to recreate AA
  2249. tx, _ = types.SignTx(types.NewTransaction(1, bb,
  2250. big.NewInt(0), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2251. b.AddTx(tx)
  2252. })
  2253. // Import the canonical chain
  2254. diskdb := rawdb.NewMemoryDatabase()
  2255. gspec.MustCommit(diskdb)
  2256. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
  2257. Debug: true,
  2258. Tracer: vm.NewJSONLogger(nil, os.Stdout),
  2259. }, nil)
  2260. if err != nil {
  2261. t.Fatalf("failed to create tester chain: %v", err)
  2262. }
  2263. if n, err := chain.InsertChain(blocks); err != nil {
  2264. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2265. }
  2266. statedb, _ := chain.State()
  2267. // If all is correct, then slot 1 and 2 are zero
  2268. if got, exp := statedb.GetState(aa, common.HexToHash("01")), (common.Hash{}); got != exp {
  2269. t.Errorf("got %x exp %x", got, exp)
  2270. }
  2271. if got, exp := statedb.GetState(aa, common.HexToHash("02")), (common.Hash{}); got != exp {
  2272. t.Errorf("got %x exp %x", got, exp)
  2273. }
  2274. // Also, 3 and 4 should be set
  2275. if got, exp := statedb.GetState(aa, common.HexToHash("03")), common.HexToHash("03"); got != exp {
  2276. t.Fatalf("got %x exp %x", got, exp)
  2277. }
  2278. if got, exp := statedb.GetState(aa, common.HexToHash("04")), common.HexToHash("04"); got != exp {
  2279. t.Fatalf("got %x exp %x", got, exp)
  2280. }
  2281. }
  2282. // TestDeleteRecreateAccount tests a state-transition that contains deletion of a
  2283. // contract with storage, and a recreate of the same contract via a
  2284. // regular value-transfer
  2285. // Expected outcome is that _all_ slots are cleared from A
  2286. func TestDeleteRecreateAccount(t *testing.T) {
  2287. var (
  2288. // Generate a canonical chain to act as the main dataset
  2289. engine = ethash.NewFaker()
  2290. db = rawdb.NewMemoryDatabase()
  2291. // A sender who makes transactions, has some funds
  2292. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2293. address = crypto.PubkeyToAddress(key.PublicKey)
  2294. funds = big.NewInt(1000000000)
  2295. aa = common.HexToAddress("0x7217d81b76bdd8707601e959454e3d776aee5f43")
  2296. aaStorage = make(map[common.Hash]common.Hash) // Initial storage in AA
  2297. aaCode = []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)} // Code for AA (simple selfdestruct)
  2298. )
  2299. // Populate two slots
  2300. aaStorage[common.HexToHash("01")] = common.HexToHash("01")
  2301. aaStorage[common.HexToHash("02")] = common.HexToHash("02")
  2302. gspec := &Genesis{
  2303. Config: params.TestChainConfig,
  2304. Alloc: GenesisAlloc{
  2305. address: {Balance: funds},
  2306. // The address 0xAAAAA selfdestructs if called
  2307. aa: {
  2308. // Code needs to just selfdestruct
  2309. Code: aaCode,
  2310. Nonce: 1,
  2311. Balance: big.NewInt(0),
  2312. Storage: aaStorage,
  2313. },
  2314. },
  2315. }
  2316. genesis := gspec.MustCommit(db)
  2317. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 1, func(i int, b *BlockGen) {
  2318. b.SetCoinbase(common.Address{1})
  2319. // One transaction to AA, to kill it
  2320. tx, _ := types.SignTx(types.NewTransaction(0, aa,
  2321. big.NewInt(0), 50000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2322. b.AddTx(tx)
  2323. // One transaction to AA, to recreate it (but without storage
  2324. tx, _ = types.SignTx(types.NewTransaction(1, aa,
  2325. big.NewInt(1), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2326. b.AddTx(tx)
  2327. })
  2328. // Import the canonical chain
  2329. diskdb := rawdb.NewMemoryDatabase()
  2330. gspec.MustCommit(diskdb)
  2331. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
  2332. Debug: true,
  2333. Tracer: vm.NewJSONLogger(nil, os.Stdout),
  2334. }, nil)
  2335. if err != nil {
  2336. t.Fatalf("failed to create tester chain: %v", err)
  2337. }
  2338. if n, err := chain.InsertChain(blocks); err != nil {
  2339. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2340. }
  2341. statedb, _ := chain.State()
  2342. // If all is correct, then both slots are zero
  2343. if got, exp := statedb.GetState(aa, common.HexToHash("01")), (common.Hash{}); got != exp {
  2344. t.Errorf("got %x exp %x", got, exp)
  2345. }
  2346. if got, exp := statedb.GetState(aa, common.HexToHash("02")), (common.Hash{}); got != exp {
  2347. t.Errorf("got %x exp %x", got, exp)
  2348. }
  2349. }
  2350. // TestDeleteRecreateSlotsAcrossManyBlocks tests multiple state-transition that contains both deletion
  2351. // and recreation of contract state.
  2352. // Contract A exists, has slots 1 and 2 set
  2353. // Tx 1: Selfdestruct A
  2354. // Tx 2: Re-create A, set slots 3 and 4
  2355. // Expected outcome is that _all_ slots are cleared from A, due to the selfdestruct,
  2356. // and then the new slots exist
  2357. func TestDeleteRecreateSlotsAcrossManyBlocks(t *testing.T) {
  2358. var (
  2359. // Generate a canonical chain to act as the main dataset
  2360. engine = ethash.NewFaker()
  2361. db = rawdb.NewMemoryDatabase()
  2362. // A sender who makes transactions, has some funds
  2363. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2364. address = crypto.PubkeyToAddress(key.PublicKey)
  2365. funds = big.NewInt(1000000000)
  2366. bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
  2367. aaStorage = make(map[common.Hash]common.Hash) // Initial storage in AA
  2368. aaCode = []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)} // Code for AA (simple selfdestruct)
  2369. )
  2370. // Populate two slots
  2371. aaStorage[common.HexToHash("01")] = common.HexToHash("01")
  2372. aaStorage[common.HexToHash("02")] = common.HexToHash("02")
  2373. // The bb-code needs to CREATE2 the aa contract. It consists of
  2374. // both initcode and deployment code
  2375. // initcode:
  2376. // 1. Set slots 3=blocknum+1, 4=4,
  2377. // 2. Return aaCode
  2378. initCode := []byte{
  2379. byte(vm.PUSH1), 0x1, //
  2380. byte(vm.NUMBER), // value = number + 1
  2381. byte(vm.ADD), //
  2382. byte(vm.PUSH1), 0x3, // location
  2383. byte(vm.SSTORE), // Set slot[3] = number + 1
  2384. byte(vm.PUSH1), 0x4, // value
  2385. byte(vm.PUSH1), 0x4, // location
  2386. byte(vm.SSTORE), // Set slot[4] = 4
  2387. // Slots are set, now return the code
  2388. byte(vm.PUSH2), byte(vm.PC), byte(vm.SELFDESTRUCT), // Push code on stack
  2389. byte(vm.PUSH1), 0x0, // memory start on stack
  2390. byte(vm.MSTORE),
  2391. // Code is now in memory.
  2392. byte(vm.PUSH1), 0x2, // size
  2393. byte(vm.PUSH1), byte(32 - 2), // offset
  2394. byte(vm.RETURN),
  2395. }
  2396. if l := len(initCode); l > 32 {
  2397. t.Fatalf("init code is too long for a pushx, need a more elaborate deployer")
  2398. }
  2399. bbCode := []byte{
  2400. // Push initcode onto stack
  2401. byte(vm.PUSH1) + byte(len(initCode)-1)}
  2402. bbCode = append(bbCode, initCode...)
  2403. bbCode = append(bbCode, []byte{
  2404. byte(vm.PUSH1), 0x0, // memory start on stack
  2405. byte(vm.MSTORE),
  2406. byte(vm.PUSH1), 0x00, // salt
  2407. byte(vm.PUSH1), byte(len(initCode)), // size
  2408. byte(vm.PUSH1), byte(32 - len(initCode)), // offset
  2409. byte(vm.PUSH1), 0x00, // endowment
  2410. byte(vm.CREATE2),
  2411. }...)
  2412. initHash := crypto.Keccak256Hash(initCode)
  2413. aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:])
  2414. t.Logf("Destination address: %x\n", aa)
  2415. gspec := &Genesis{
  2416. Config: params.TestChainConfig,
  2417. Alloc: GenesisAlloc{
  2418. address: {Balance: funds},
  2419. // The address 0xAAAAA selfdestructs if called
  2420. aa: {
  2421. // Code needs to just selfdestruct
  2422. Code: aaCode,
  2423. Nonce: 1,
  2424. Balance: big.NewInt(0),
  2425. Storage: aaStorage,
  2426. },
  2427. // The contract BB recreates AA
  2428. bb: {
  2429. Code: bbCode,
  2430. Balance: big.NewInt(1),
  2431. },
  2432. },
  2433. }
  2434. genesis := gspec.MustCommit(db)
  2435. var nonce uint64
  2436. type expectation struct {
  2437. exist bool
  2438. blocknum int
  2439. values map[int]int
  2440. }
  2441. var current = &expectation{
  2442. exist: true, // exists in genesis
  2443. blocknum: 0,
  2444. values: map[int]int{1: 1, 2: 2},
  2445. }
  2446. var expectations []*expectation
  2447. var newDestruct = func(e *expectation) *types.Transaction {
  2448. tx, _ := types.SignTx(types.NewTransaction(nonce, aa,
  2449. big.NewInt(0), 50000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2450. nonce++
  2451. if e.exist {
  2452. e.exist = false
  2453. e.values = nil
  2454. }
  2455. t.Logf("block %d; adding destruct\n", e.blocknum)
  2456. return tx
  2457. }
  2458. var newResurrect = func(e *expectation) *types.Transaction {
  2459. tx, _ := types.SignTx(types.NewTransaction(nonce, bb,
  2460. big.NewInt(0), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2461. nonce++
  2462. if !e.exist {
  2463. e.exist = true
  2464. e.values = map[int]int{3: e.blocknum + 1, 4: 4}
  2465. }
  2466. t.Logf("block %d; adding resurrect\n", e.blocknum)
  2467. return tx
  2468. }
  2469. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 150, func(i int, b *BlockGen) {
  2470. var exp = new(expectation)
  2471. exp.blocknum = i + 1
  2472. exp.values = make(map[int]int)
  2473. for k, v := range current.values {
  2474. exp.values[k] = v
  2475. }
  2476. exp.exist = current.exist
  2477. b.SetCoinbase(common.Address{1})
  2478. if i%2 == 0 {
  2479. b.AddTx(newDestruct(exp))
  2480. }
  2481. if i%3 == 0 {
  2482. b.AddTx(newResurrect(exp))
  2483. }
  2484. if i%5 == 0 {
  2485. b.AddTx(newDestruct(exp))
  2486. }
  2487. if i%7 == 0 {
  2488. b.AddTx(newResurrect(exp))
  2489. }
  2490. expectations = append(expectations, exp)
  2491. current = exp
  2492. })
  2493. // Import the canonical chain
  2494. diskdb := rawdb.NewMemoryDatabase()
  2495. gspec.MustCommit(diskdb)
  2496. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
  2497. //Debug: true,
  2498. //Tracer: vm.NewJSONLogger(nil, os.Stdout),
  2499. }, nil)
  2500. if err != nil {
  2501. t.Fatalf("failed to create tester chain: %v", err)
  2502. }
  2503. var asHash = func(num int) common.Hash {
  2504. return common.BytesToHash([]byte{byte(num)})
  2505. }
  2506. for i, block := range blocks {
  2507. blockNum := i + 1
  2508. if n, err := chain.InsertChain([]*types.Block{block}); err != nil {
  2509. t.Fatalf("block %d: failed to insert into chain: %v", n, err)
  2510. }
  2511. statedb, _ := chain.State()
  2512. // If all is correct, then slot 1 and 2 are zero
  2513. if got, exp := statedb.GetState(aa, common.HexToHash("01")), (common.Hash{}); got != exp {
  2514. t.Errorf("block %d, got %x exp %x", blockNum, got, exp)
  2515. }
  2516. if got, exp := statedb.GetState(aa, common.HexToHash("02")), (common.Hash{}); got != exp {
  2517. t.Errorf("block %d, got %x exp %x", blockNum, got, exp)
  2518. }
  2519. exp := expectations[i]
  2520. if exp.exist {
  2521. if !statedb.Exist(aa) {
  2522. t.Fatalf("block %d, expected %v to exist, it did not", blockNum, aa)
  2523. }
  2524. for slot, val := range exp.values {
  2525. if gotValue, expValue := statedb.GetState(aa, asHash(slot)), asHash(val); gotValue != expValue {
  2526. t.Fatalf("block %d, slot %d, got %x exp %x", blockNum, slot, gotValue, expValue)
  2527. }
  2528. }
  2529. } else {
  2530. if statedb.Exist(aa) {
  2531. t.Fatalf("block %d, expected %v to not exist, it did", blockNum, aa)
  2532. }
  2533. }
  2534. }
  2535. }
  2536. // TestInitThenFailCreateContract tests a pretty notorious case that happened
  2537. // on mainnet over blocks 7338108, 7338110 and 7338115.
  2538. // - Block 7338108: address e771789f5cccac282f23bb7add5690e1f6ca467c is initiated
  2539. // with 0.001 ether (thus created but no code)
  2540. // - Block 7338110: a CREATE2 is attempted. The CREATE2 would deploy code on
  2541. // the same address e771789f5cccac282f23bb7add5690e1f6ca467c. However, the
  2542. // deployment fails due to OOG during initcode execution
  2543. // - Block 7338115: another tx checks the balance of
  2544. // e771789f5cccac282f23bb7add5690e1f6ca467c, and the snapshotter returned it as
  2545. // zero.
  2546. //
  2547. // The problem being that the snapshotter maintains a destructset, and adds items
  2548. // to the destructset in case something is created "onto" an existing item.
  2549. // We need to either roll back the snapDestructs, or not place it into snapDestructs
  2550. // in the first place.
  2551. //
  2552. func TestInitThenFailCreateContract(t *testing.T) {
  2553. var (
  2554. // Generate a canonical chain to act as the main dataset
  2555. engine = ethash.NewFaker()
  2556. db = rawdb.NewMemoryDatabase()
  2557. // A sender who makes transactions, has some funds
  2558. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  2559. address = crypto.PubkeyToAddress(key.PublicKey)
  2560. funds = big.NewInt(1000000000)
  2561. bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
  2562. )
  2563. // The bb-code needs to CREATE2 the aa contract. It consists of
  2564. // both initcode and deployment code
  2565. // initcode:
  2566. // 1. If blocknum < 1, error out (e.g invalid opcode)
  2567. // 2. else, return a snippet of code
  2568. initCode := []byte{
  2569. byte(vm.PUSH1), 0x1, // y (2)
  2570. byte(vm.NUMBER), // x (number)
  2571. byte(vm.GT), // x > y?
  2572. byte(vm.PUSH1), byte(0x8),
  2573. byte(vm.JUMPI), // jump to label if number > 2
  2574. byte(0xFE), // illegal opcode
  2575. byte(vm.JUMPDEST),
  2576. byte(vm.PUSH1), 0x2, // size
  2577. byte(vm.PUSH1), 0x0, // offset
  2578. byte(vm.RETURN), // return 2 bytes of zero-code
  2579. }
  2580. if l := len(initCode); l > 32 {
  2581. t.Fatalf("init code is too long for a pushx, need a more elaborate deployer")
  2582. }
  2583. bbCode := []byte{
  2584. // Push initcode onto stack
  2585. byte(vm.PUSH1) + byte(len(initCode)-1)}
  2586. bbCode = append(bbCode, initCode...)
  2587. bbCode = append(bbCode, []byte{
  2588. byte(vm.PUSH1), 0x0, // memory start on stack
  2589. byte(vm.MSTORE),
  2590. byte(vm.PUSH1), 0x00, // salt
  2591. byte(vm.PUSH1), byte(len(initCode)), // size
  2592. byte(vm.PUSH1), byte(32 - len(initCode)), // offset
  2593. byte(vm.PUSH1), 0x00, // endowment
  2594. byte(vm.CREATE2),
  2595. }...)
  2596. initHash := crypto.Keccak256Hash(initCode)
  2597. aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:])
  2598. t.Logf("Destination address: %x\n", aa)
  2599. gspec := &Genesis{
  2600. Config: params.TestChainConfig,
  2601. Alloc: GenesisAlloc{
  2602. address: {Balance: funds},
  2603. // The address aa has some funds
  2604. aa: {Balance: big.NewInt(100000)},
  2605. // The contract BB tries to create code onto AA
  2606. bb: {
  2607. Code: bbCode,
  2608. Balance: big.NewInt(1),
  2609. },
  2610. },
  2611. }
  2612. genesis := gspec.MustCommit(db)
  2613. nonce := uint64(0)
  2614. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 4, func(i int, b *BlockGen) {
  2615. b.SetCoinbase(common.Address{1})
  2616. // One transaction to BB
  2617. tx, _ := types.SignTx(types.NewTransaction(nonce, bb,
  2618. big.NewInt(0), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
  2619. b.AddTx(tx)
  2620. nonce++
  2621. })
  2622. // Import the canonical chain
  2623. diskdb := rawdb.NewMemoryDatabase()
  2624. gspec.MustCommit(diskdb)
  2625. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
  2626. //Debug: true,
  2627. //Tracer: vm.NewJSONLogger(nil, os.Stdout),
  2628. }, nil)
  2629. if err != nil {
  2630. t.Fatalf("failed to create tester chain: %v", err)
  2631. }
  2632. statedb, _ := chain.State()
  2633. if got, exp := statedb.GetBalance(aa), big.NewInt(100000); got.Cmp(exp) != 0 {
  2634. t.Fatalf("Genesis err, got %v exp %v", got, exp)
  2635. }
  2636. // First block tries to create, but fails
  2637. {
  2638. block := blocks[0]
  2639. if _, err := chain.InsertChain([]*types.Block{blocks[0]}); err != nil {
  2640. t.Fatalf("block %d: failed to insert into chain: %v", block.NumberU64(), err)
  2641. }
  2642. statedb, _ = chain.State()
  2643. if got, exp := statedb.GetBalance(aa), big.NewInt(100000); got.Cmp(exp) != 0 {
  2644. t.Fatalf("block %d: got %v exp %v", block.NumberU64(), got, exp)
  2645. }
  2646. }
  2647. // Import the rest of the blocks
  2648. for _, block := range blocks[1:] {
  2649. if _, err := chain.InsertChain([]*types.Block{block}); err != nil {
  2650. t.Fatalf("block %d: failed to insert into chain: %v", block.NumberU64(), err)
  2651. }
  2652. }
  2653. }