blockchain_test.go 142 KB

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