blockchain_test.go 106 KB

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