blockchain_test.go 115 KB

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