blockchain_test.go 115 KB

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