blockchain_test.go 112 KB

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