blockchain_test.go 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "fmt"
  19. "math/big"
  20. "math/rand"
  21. "sync"
  22. "testing"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/consensus/ethash"
  26. "github.com/ethereum/go-ethereum/core/state"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/core/vm"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/params"
  32. )
  33. // Test fork of length N starting from block i
  34. func testFork(t *testing.T, blockchain *BlockChain, i, n int, full bool, comparator func(td1, td2 *big.Int)) {
  35. // Copy old chain up to #i into a new db
  36. db, blockchain2, err := newCanonical(ethash.NewFaker(), i, full)
  37. if err != nil {
  38. t.Fatal("could not make new canonical in testFork", err)
  39. }
  40. defer blockchain2.Stop()
  41. // Assert the chains have the same header/block at #i
  42. var hash1, hash2 common.Hash
  43. if full {
  44. hash1 = blockchain.GetBlockByNumber(uint64(i)).Hash()
  45. hash2 = blockchain2.GetBlockByNumber(uint64(i)).Hash()
  46. } else {
  47. hash1 = blockchain.GetHeaderByNumber(uint64(i)).Hash()
  48. hash2 = blockchain2.GetHeaderByNumber(uint64(i)).Hash()
  49. }
  50. if hash1 != hash2 {
  51. t.Errorf("chain content mismatch at %d: have hash %v, want hash %v", i, hash2, hash1)
  52. }
  53. // Extend the newly created chain
  54. var (
  55. blockChainB []*types.Block
  56. headerChainB []*types.Header
  57. )
  58. if full {
  59. blockChainB = makeBlockChain(blockchain2.CurrentBlock(), n, ethash.NewFaker(), db, forkSeed)
  60. if _, err := blockchain2.InsertChain(blockChainB); err != nil {
  61. t.Fatalf("failed to insert forking chain: %v", err)
  62. }
  63. } else {
  64. headerChainB = makeHeaderChain(blockchain2.CurrentHeader(), n, ethash.NewFaker(), db, forkSeed)
  65. if _, err := blockchain2.InsertHeaderChain(headerChainB, 1); err != nil {
  66. t.Fatalf("failed to insert forking chain: %v", err)
  67. }
  68. }
  69. // Sanity check that the forked chain can be imported into the original
  70. var tdPre, tdPost *big.Int
  71. if full {
  72. tdPre = blockchain.GetTdByHash(blockchain.CurrentBlock().Hash())
  73. if err := testBlockChainImport(blockChainB, blockchain); err != nil {
  74. t.Fatalf("failed to import forked block chain: %v", err)
  75. }
  76. tdPost = blockchain.GetTdByHash(blockChainB[len(blockChainB)-1].Hash())
  77. } else {
  78. tdPre = blockchain.GetTdByHash(blockchain.CurrentHeader().Hash())
  79. if err := testHeaderChainImport(headerChainB, blockchain); err != nil {
  80. t.Fatalf("failed to import forked header chain: %v", err)
  81. }
  82. tdPost = blockchain.GetTdByHash(headerChainB[len(headerChainB)-1].Hash())
  83. }
  84. // Compare the total difficulties of the chains
  85. comparator(tdPre, tdPost)
  86. }
  87. func printChain(bc *BlockChain) {
  88. for i := bc.CurrentBlock().Number().Uint64(); i > 0; i-- {
  89. b := bc.GetBlockByNumber(uint64(i))
  90. fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty())
  91. }
  92. }
  93. // testBlockChainImport tries to process a chain of blocks, writing them into
  94. // the database if successful.
  95. func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error {
  96. for _, block := range chain {
  97. // Try and process the block
  98. err := blockchain.engine.VerifyHeader(blockchain, block.Header(), true)
  99. if err == nil {
  100. err = blockchain.validator.ValidateBody(block)
  101. }
  102. if err != nil {
  103. if err == ErrKnownBlock {
  104. continue
  105. }
  106. return err
  107. }
  108. statedb, err := state.New(blockchain.GetBlockByHash(block.ParentHash()).Root(), blockchain.stateCache)
  109. if err != nil {
  110. return err
  111. }
  112. receipts, _, usedGas, err := blockchain.Processor().Process(block, statedb, vm.Config{})
  113. if err != nil {
  114. blockchain.reportBlock(block, receipts, err)
  115. return err
  116. }
  117. err = blockchain.validator.ValidateState(block, blockchain.GetBlockByHash(block.ParentHash()), statedb, receipts, usedGas)
  118. if err != nil {
  119. blockchain.reportBlock(block, receipts, err)
  120. return err
  121. }
  122. blockchain.mu.Lock()
  123. WriteTd(blockchain.db, block.Hash(), block.NumberU64(), new(big.Int).Add(block.Difficulty(), blockchain.GetTdByHash(block.ParentHash())))
  124. WriteBlock(blockchain.db, block)
  125. statedb.Commit(false)
  126. blockchain.mu.Unlock()
  127. }
  128. return nil
  129. }
  130. // testHeaderChainImport tries to process a chain of header, writing them into
  131. // the database if successful.
  132. func testHeaderChainImport(chain []*types.Header, blockchain *BlockChain) error {
  133. for _, header := range chain {
  134. // Try and validate the header
  135. if err := blockchain.engine.VerifyHeader(blockchain, header, false); err != nil {
  136. return err
  137. }
  138. // Manually insert the header into the database, but don't reorganise (allows subsequent testing)
  139. blockchain.mu.Lock()
  140. WriteTd(blockchain.db, header.Hash(), header.Number.Uint64(), new(big.Int).Add(header.Difficulty, blockchain.GetTdByHash(header.ParentHash)))
  141. WriteHeader(blockchain.db, header)
  142. blockchain.mu.Unlock()
  143. }
  144. return nil
  145. }
  146. func insertChain(done chan bool, blockchain *BlockChain, chain types.Blocks, t *testing.T) {
  147. _, err := blockchain.InsertChain(chain)
  148. if err != nil {
  149. fmt.Println(err)
  150. t.FailNow()
  151. }
  152. done <- true
  153. }
  154. func TestLastBlock(t *testing.T) {
  155. _, blockchain, err := newCanonical(ethash.NewFaker(), 0, true)
  156. if err != nil {
  157. t.Fatalf("failed to create pristine chain: %v", err)
  158. }
  159. defer blockchain.Stop()
  160. blocks := makeBlockChain(blockchain.CurrentBlock(), 1, ethash.NewFullFaker(), blockchain.db, 0)
  161. if _, err := blockchain.InsertChain(blocks); err != nil {
  162. t.Fatalf("Failed to insert block: %v", err)
  163. }
  164. if blocks[len(blocks)-1].Hash() != GetHeadBlockHash(blockchain.db) {
  165. t.Fatalf("Write/Get HeadBlockHash failed")
  166. }
  167. }
  168. // Tests that given a starting canonical chain of a given size, it can be extended
  169. // with various length chains.
  170. func TestExtendCanonicalHeaders(t *testing.T) { testExtendCanonical(t, false) }
  171. func TestExtendCanonicalBlocks(t *testing.T) { testExtendCanonical(t, true) }
  172. func testExtendCanonical(t *testing.T, full bool) {
  173. length := 5
  174. // Make first chain starting from genesis
  175. _, processor, err := newCanonical(ethash.NewFaker(), length, full)
  176. if err != nil {
  177. t.Fatalf("failed to make new canonical chain: %v", err)
  178. }
  179. defer processor.Stop()
  180. // Define the difficulty comparator
  181. better := func(td1, td2 *big.Int) {
  182. if td2.Cmp(td1) <= 0 {
  183. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  184. }
  185. }
  186. // Start fork from current height
  187. testFork(t, processor, length, 1, full, better)
  188. testFork(t, processor, length, 2, full, better)
  189. testFork(t, processor, length, 5, full, better)
  190. testFork(t, processor, length, 10, full, better)
  191. }
  192. // Tests that given a starting canonical chain of a given size, creating shorter
  193. // forks do not take canonical ownership.
  194. func TestShorterForkHeaders(t *testing.T) { testShorterFork(t, false) }
  195. func TestShorterForkBlocks(t *testing.T) { testShorterFork(t, true) }
  196. func testShorterFork(t *testing.T, full bool) {
  197. length := 10
  198. // Make first chain starting from genesis
  199. _, processor, err := newCanonical(ethash.NewFaker(), length, full)
  200. if err != nil {
  201. t.Fatalf("failed to make new canonical chain: %v", err)
  202. }
  203. defer processor.Stop()
  204. // Define the difficulty comparator
  205. worse := func(td1, td2 *big.Int) {
  206. if td2.Cmp(td1) >= 0 {
  207. t.Errorf("total difficulty mismatch: have %v, expected less than %v", td2, td1)
  208. }
  209. }
  210. // Sum of numbers must be less than `length` for this to be a shorter fork
  211. testFork(t, processor, 0, 3, full, worse)
  212. testFork(t, processor, 0, 7, full, worse)
  213. testFork(t, processor, 1, 1, full, worse)
  214. testFork(t, processor, 1, 7, full, worse)
  215. testFork(t, processor, 5, 3, full, worse)
  216. testFork(t, processor, 5, 4, full, worse)
  217. }
  218. // Tests that given a starting canonical chain of a given size, creating longer
  219. // forks do take canonical ownership.
  220. func TestLongerForkHeaders(t *testing.T) { testLongerFork(t, false) }
  221. func TestLongerForkBlocks(t *testing.T) { testLongerFork(t, true) }
  222. func testLongerFork(t *testing.T, full bool) {
  223. length := 10
  224. // Make first chain starting from genesis
  225. _, processor, err := newCanonical(ethash.NewFaker(), length, full)
  226. if err != nil {
  227. t.Fatalf("failed to make new canonical chain: %v", err)
  228. }
  229. defer processor.Stop()
  230. // Define the difficulty comparator
  231. better := func(td1, td2 *big.Int) {
  232. if td2.Cmp(td1) <= 0 {
  233. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  234. }
  235. }
  236. // Sum of numbers must be greater than `length` for this to be a longer fork
  237. testFork(t, processor, 0, 11, full, better)
  238. testFork(t, processor, 0, 15, full, better)
  239. testFork(t, processor, 1, 10, full, better)
  240. testFork(t, processor, 1, 12, full, better)
  241. testFork(t, processor, 5, 6, full, better)
  242. testFork(t, processor, 5, 8, full, better)
  243. }
  244. // Tests that given a starting canonical chain of a given size, creating equal
  245. // forks do take canonical ownership.
  246. func TestEqualForkHeaders(t *testing.T) { testEqualFork(t, false) }
  247. func TestEqualForkBlocks(t *testing.T) { testEqualFork(t, true) }
  248. func testEqualFork(t *testing.T, full bool) {
  249. length := 10
  250. // Make first chain starting from genesis
  251. _, processor, err := newCanonical(ethash.NewFaker(), length, full)
  252. if err != nil {
  253. t.Fatalf("failed to make new canonical chain: %v", err)
  254. }
  255. defer processor.Stop()
  256. // Define the difficulty comparator
  257. equal := func(td1, td2 *big.Int) {
  258. if td2.Cmp(td1) != 0 {
  259. t.Errorf("total difficulty mismatch: have %v, want %v", td2, td1)
  260. }
  261. }
  262. // Sum of numbers must be equal to `length` for this to be an equal fork
  263. testFork(t, processor, 0, 10, full, equal)
  264. testFork(t, processor, 1, 9, full, equal)
  265. testFork(t, processor, 2, 8, full, equal)
  266. testFork(t, processor, 5, 5, full, equal)
  267. testFork(t, processor, 6, 4, full, equal)
  268. testFork(t, processor, 9, 1, full, equal)
  269. }
  270. // Tests that chains missing links do not get accepted by the processor.
  271. func TestBrokenHeaderChain(t *testing.T) { testBrokenChain(t, false) }
  272. func TestBrokenBlockChain(t *testing.T) { testBrokenChain(t, true) }
  273. func testBrokenChain(t *testing.T, full bool) {
  274. // Make chain starting from genesis
  275. db, blockchain, err := newCanonical(ethash.NewFaker(), 10, full)
  276. if err != nil {
  277. t.Fatalf("failed to make new canonical chain: %v", err)
  278. }
  279. defer blockchain.Stop()
  280. // Create a forked chain, and try to insert with a missing link
  281. if full {
  282. chain := makeBlockChain(blockchain.CurrentBlock(), 5, ethash.NewFaker(), db, forkSeed)[1:]
  283. if err := testBlockChainImport(chain, blockchain); err == nil {
  284. t.Errorf("broken block chain not reported")
  285. }
  286. } else {
  287. chain := makeHeaderChain(blockchain.CurrentHeader(), 5, ethash.NewFaker(), db, forkSeed)[1:]
  288. if err := testHeaderChainImport(chain, blockchain); err == nil {
  289. t.Errorf("broken header chain not reported")
  290. }
  291. }
  292. }
  293. // Tests that reorganising a long difficult chain after a short easy one
  294. // overwrites the canonical numbers and links in the database.
  295. func TestReorgLongHeaders(t *testing.T) { testReorgLong(t, false) }
  296. func TestReorgLongBlocks(t *testing.T) { testReorgLong(t, true) }
  297. func testReorgLong(t *testing.T, full bool) {
  298. testReorg(t, []int64{0, 0, -9}, []int64{0, 0, 0, -9}, 393280, full)
  299. }
  300. // Tests that reorganising a short difficult chain after a long easy one
  301. // overwrites the canonical numbers and links in the database.
  302. func TestReorgShortHeaders(t *testing.T) { testReorgShort(t, false) }
  303. func TestReorgShortBlocks(t *testing.T) { testReorgShort(t, true) }
  304. func testReorgShort(t *testing.T, full bool) {
  305. // Create a long easy chain vs. a short heavy one. Due to difficulty adjustment
  306. // we need a fairly long chain of blocks with different difficulties for a short
  307. // one to become heavyer than a long one. The 96 is an empirical value.
  308. easy := make([]int64, 96)
  309. for i := 0; i < len(easy); i++ {
  310. easy[i] = 60
  311. }
  312. diff := make([]int64, len(easy)-1)
  313. for i := 0; i < len(diff); i++ {
  314. diff[i] = -9
  315. }
  316. testReorg(t, easy, diff, 12615120, full)
  317. }
  318. func testReorg(t *testing.T, first, second []int64, td int64, full bool) {
  319. // Create a pristine chain and database
  320. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full)
  321. if err != nil {
  322. t.Fatalf("failed to create pristine chain: %v", err)
  323. }
  324. defer blockchain.Stop()
  325. // Insert an easy and a difficult chain afterwards
  326. easyBlocks, _ := GenerateChain(params.TestChainConfig, blockchain.CurrentBlock(), ethash.NewFaker(), db, len(first), func(i int, b *BlockGen) {
  327. b.OffsetTime(first[i])
  328. })
  329. diffBlocks, _ := GenerateChain(params.TestChainConfig, blockchain.CurrentBlock(), ethash.NewFaker(), db, len(second), func(i int, b *BlockGen) {
  330. b.OffsetTime(second[i])
  331. })
  332. if full {
  333. if _, err := blockchain.InsertChain(easyBlocks); err != nil {
  334. t.Fatalf("failed to insert easy chain: %v", err)
  335. }
  336. if _, err := blockchain.InsertChain(diffBlocks); err != nil {
  337. t.Fatalf("failed to insert difficult chain: %v", err)
  338. }
  339. } else {
  340. easyHeaders := make([]*types.Header, len(easyBlocks))
  341. for i, block := range easyBlocks {
  342. easyHeaders[i] = block.Header()
  343. }
  344. diffHeaders := make([]*types.Header, len(diffBlocks))
  345. for i, block := range diffBlocks {
  346. diffHeaders[i] = block.Header()
  347. }
  348. if _, err := blockchain.InsertHeaderChain(easyHeaders, 1); err != nil {
  349. t.Fatalf("failed to insert easy chain: %v", err)
  350. }
  351. if _, err := blockchain.InsertHeaderChain(diffHeaders, 1); err != nil {
  352. t.Fatalf("failed to insert difficult chain: %v", err)
  353. }
  354. }
  355. // Check that the chain is valid number and link wise
  356. if full {
  357. prev := blockchain.CurrentBlock()
  358. for block := blockchain.GetBlockByNumber(blockchain.CurrentBlock().NumberU64() - 1); block.NumberU64() != 0; prev, block = block, blockchain.GetBlockByNumber(block.NumberU64()-1) {
  359. if prev.ParentHash() != block.Hash() {
  360. t.Errorf("parent block hash mismatch: have %x, want %x", prev.ParentHash(), block.Hash())
  361. }
  362. }
  363. } else {
  364. prev := blockchain.CurrentHeader()
  365. for header := blockchain.GetHeaderByNumber(blockchain.CurrentHeader().Number.Uint64() - 1); header.Number.Uint64() != 0; prev, header = header, blockchain.GetHeaderByNumber(header.Number.Uint64()-1) {
  366. if prev.ParentHash != header.Hash() {
  367. t.Errorf("parent header hash mismatch: have %x, want %x", prev.ParentHash, header.Hash())
  368. }
  369. }
  370. }
  371. // Make sure the chain total difficulty is the correct one
  372. want := new(big.Int).Add(blockchain.genesisBlock.Difficulty(), big.NewInt(td))
  373. if full {
  374. if have := blockchain.GetTdByHash(blockchain.CurrentBlock().Hash()); have.Cmp(want) != 0 {
  375. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  376. }
  377. } else {
  378. if have := blockchain.GetTdByHash(blockchain.CurrentHeader().Hash()); have.Cmp(want) != 0 {
  379. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  380. }
  381. }
  382. }
  383. // Tests that the insertion functions detect banned hashes.
  384. func TestBadHeaderHashes(t *testing.T) { testBadHashes(t, false) }
  385. func TestBadBlockHashes(t *testing.T) { testBadHashes(t, true) }
  386. func testBadHashes(t *testing.T, full bool) {
  387. // Create a pristine chain and database
  388. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full)
  389. if err != nil {
  390. t.Fatalf("failed to create pristine chain: %v", err)
  391. }
  392. defer blockchain.Stop()
  393. // Create a chain, ban a hash and try to import
  394. if full {
  395. blocks := makeBlockChain(blockchain.CurrentBlock(), 3, ethash.NewFaker(), db, 10)
  396. BadHashes[blocks[2].Header().Hash()] = true
  397. defer func() { delete(BadHashes, blocks[2].Header().Hash()) }()
  398. _, err = blockchain.InsertChain(blocks)
  399. } else {
  400. headers := makeHeaderChain(blockchain.CurrentHeader(), 3, ethash.NewFaker(), db, 10)
  401. BadHashes[headers[2].Hash()] = true
  402. defer func() { delete(BadHashes, headers[2].Hash()) }()
  403. _, err = blockchain.InsertHeaderChain(headers, 1)
  404. }
  405. if err != ErrBlacklistedHash {
  406. t.Errorf("error mismatch: have: %v, want: %v", err, ErrBlacklistedHash)
  407. }
  408. }
  409. // Tests that bad hashes are detected on boot, and the chain rolled back to a
  410. // good state prior to the bad hash.
  411. func TestReorgBadHeaderHashes(t *testing.T) { testReorgBadHashes(t, false) }
  412. func TestReorgBadBlockHashes(t *testing.T) { testReorgBadHashes(t, true) }
  413. func testReorgBadHashes(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. // Create a chain, import and ban afterwards
  420. headers := makeHeaderChain(blockchain.CurrentHeader(), 4, ethash.NewFaker(), db, 10)
  421. blocks := makeBlockChain(blockchain.CurrentBlock(), 4, ethash.NewFaker(), db, 10)
  422. if full {
  423. if _, err = blockchain.InsertChain(blocks); err != nil {
  424. t.Errorf("failed to import blocks: %v", err)
  425. }
  426. if blockchain.CurrentBlock().Hash() != blocks[3].Hash() {
  427. t.Errorf("last block hash mismatch: have: %x, want %x", blockchain.CurrentBlock().Hash(), blocks[3].Header().Hash())
  428. }
  429. BadHashes[blocks[3].Header().Hash()] = true
  430. defer func() { delete(BadHashes, blocks[3].Header().Hash()) }()
  431. } else {
  432. if _, err = blockchain.InsertHeaderChain(headers, 1); err != nil {
  433. t.Errorf("failed to import headers: %v", err)
  434. }
  435. if blockchain.CurrentHeader().Hash() != headers[3].Hash() {
  436. t.Errorf("last header hash mismatch: have: %x, want %x", blockchain.CurrentHeader().Hash(), headers[3].Hash())
  437. }
  438. BadHashes[headers[3].Hash()] = true
  439. defer func() { delete(BadHashes, headers[3].Hash()) }()
  440. }
  441. blockchain.Stop()
  442. // Create a new BlockChain and check that it rolled back the state.
  443. ncm, err := NewBlockChain(blockchain.db, nil, blockchain.chainConfig, ethash.NewFaker(), vm.Config{})
  444. if err != nil {
  445. t.Fatalf("failed to create new chain manager: %v", err)
  446. }
  447. if full {
  448. if ncm.CurrentBlock().Hash() != blocks[2].Header().Hash() {
  449. t.Errorf("last block hash mismatch: have: %x, want %x", ncm.CurrentBlock().Hash(), blocks[2].Header().Hash())
  450. }
  451. if blocks[2].Header().GasLimit != ncm.GasLimit() {
  452. t.Errorf("last block gasLimit mismatch: have: %d, want %d", ncm.GasLimit(), blocks[2].Header().GasLimit)
  453. }
  454. } else {
  455. if ncm.CurrentHeader().Hash() != headers[2].Hash() {
  456. t.Errorf("last header hash mismatch: have: %x, want %x", ncm.CurrentHeader().Hash(), headers[2].Hash())
  457. }
  458. }
  459. ncm.Stop()
  460. }
  461. // Tests chain insertions in the face of one entity containing an invalid nonce.
  462. func TestHeadersInsertNonceError(t *testing.T) { testInsertNonceError(t, false) }
  463. func TestBlocksInsertNonceError(t *testing.T) { testInsertNonceError(t, true) }
  464. func testInsertNonceError(t *testing.T, full bool) {
  465. for i := 1; i < 25 && !t.Failed(); i++ {
  466. // Create a pristine chain and database
  467. db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full)
  468. if err != nil {
  469. t.Fatalf("failed to create pristine chain: %v", err)
  470. }
  471. defer blockchain.Stop()
  472. // Create and insert a chain with a failing nonce
  473. var (
  474. failAt int
  475. failRes int
  476. failNum uint64
  477. )
  478. if full {
  479. blocks := makeBlockChain(blockchain.CurrentBlock(), i, ethash.NewFaker(), db, 0)
  480. failAt = rand.Int() % len(blocks)
  481. failNum = blocks[failAt].NumberU64()
  482. blockchain.engine = ethash.NewFakeFailer(failNum)
  483. failRes, err = blockchain.InsertChain(blocks)
  484. } else {
  485. headers := makeHeaderChain(blockchain.CurrentHeader(), i, ethash.NewFaker(), db, 0)
  486. failAt = rand.Int() % len(headers)
  487. failNum = headers[failAt].Number.Uint64()
  488. blockchain.engine = ethash.NewFakeFailer(failNum)
  489. blockchain.hc.engine = blockchain.engine
  490. failRes, err = blockchain.InsertHeaderChain(headers, 1)
  491. }
  492. // Check that the returned error indicates the failure.
  493. if failRes != failAt {
  494. t.Errorf("test %d: failure index mismatch: have %d, want %d", i, failRes, failAt)
  495. }
  496. // Check that all no blocks after the failing block have been inserted.
  497. for j := 0; j < i-failAt; j++ {
  498. if full {
  499. if block := blockchain.GetBlockByNumber(failNum + uint64(j)); block != nil {
  500. t.Errorf("test %d: invalid block in chain: %v", i, block)
  501. }
  502. } else {
  503. if header := blockchain.GetHeaderByNumber(failNum + uint64(j)); header != nil {
  504. t.Errorf("test %d: invalid header in chain: %v", i, header)
  505. }
  506. }
  507. }
  508. }
  509. }
  510. // Tests that fast importing a block chain produces the same chain data as the
  511. // classical full block processing.
  512. func TestFastVsFullChains(t *testing.T) {
  513. // Configure and generate a sample block chain
  514. var (
  515. gendb, _ = ethdb.NewMemDatabase()
  516. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  517. address = crypto.PubkeyToAddress(key.PublicKey)
  518. funds = big.NewInt(1000000000)
  519. gspec = &Genesis{
  520. Config: params.TestChainConfig,
  521. Alloc: GenesisAlloc{address: {Balance: funds}},
  522. }
  523. genesis = gspec.MustCommit(gendb)
  524. signer = types.NewEIP155Signer(gspec.Config.ChainId)
  525. )
  526. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, 1024, func(i int, block *BlockGen) {
  527. block.SetCoinbase(common.Address{0x00})
  528. // If the block number is multiple of 3, send a few bonus transactions to the miner
  529. if i%3 == 2 {
  530. for j := 0; j < i%4+1; j++ {
  531. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, nil, nil), signer, key)
  532. if err != nil {
  533. panic(err)
  534. }
  535. block.AddTx(tx)
  536. }
  537. }
  538. // If the block number is a multiple of 5, add a few bonus uncles to the block
  539. if i%5 == 5 {
  540. block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
  541. }
  542. })
  543. // Import the chain as an archive node for the comparison baseline
  544. archiveDb, _ := ethdb.NewMemDatabase()
  545. gspec.MustCommit(archiveDb)
  546. archive, _ := NewBlockChain(archiveDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  547. defer archive.Stop()
  548. if n, err := archive.InsertChain(blocks); err != nil {
  549. t.Fatalf("failed to process block %d: %v", n, err)
  550. }
  551. // Fast import the chain as a non-archive node to test
  552. fastDb, _ := ethdb.NewMemDatabase()
  553. gspec.MustCommit(fastDb)
  554. fast, _ := NewBlockChain(fastDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  555. defer fast.Stop()
  556. headers := make([]*types.Header, len(blocks))
  557. for i, block := range blocks {
  558. headers[i] = block.Header()
  559. }
  560. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  561. t.Fatalf("failed to insert header %d: %v", n, err)
  562. }
  563. if n, err := fast.InsertReceiptChain(blocks, receipts); err != nil {
  564. t.Fatalf("failed to insert receipt %d: %v", n, err)
  565. }
  566. // Iterate over all chain data components, and cross reference
  567. for i := 0; i < len(blocks); i++ {
  568. num, hash := blocks[i].NumberU64(), blocks[i].Hash()
  569. if ftd, atd := fast.GetTdByHash(hash), archive.GetTdByHash(hash); ftd.Cmp(atd) != 0 {
  570. t.Errorf("block #%d [%x]: td mismatch: have %v, want %v", num, hash, ftd, atd)
  571. }
  572. if fheader, aheader := fast.GetHeaderByHash(hash), archive.GetHeaderByHash(hash); fheader.Hash() != aheader.Hash() {
  573. t.Errorf("block #%d [%x]: header mismatch: have %v, want %v", num, hash, fheader, aheader)
  574. }
  575. if fblock, ablock := fast.GetBlockByHash(hash), archive.GetBlockByHash(hash); fblock.Hash() != ablock.Hash() {
  576. t.Errorf("block #%d [%x]: block mismatch: have %v, want %v", num, hash, fblock, ablock)
  577. } else if types.DeriveSha(fblock.Transactions()) != types.DeriveSha(ablock.Transactions()) {
  578. t.Errorf("block #%d [%x]: transactions mismatch: have %v, want %v", num, hash, fblock.Transactions(), ablock.Transactions())
  579. } else if types.CalcUncleHash(fblock.Uncles()) != types.CalcUncleHash(ablock.Uncles()) {
  580. t.Errorf("block #%d [%x]: uncles mismatch: have %v, want %v", num, hash, fblock.Uncles(), ablock.Uncles())
  581. }
  582. if freceipts, areceipts := GetBlockReceipts(fastDb, hash, GetBlockNumber(fastDb, hash)), GetBlockReceipts(archiveDb, hash, GetBlockNumber(archiveDb, hash)); types.DeriveSha(freceipts) != types.DeriveSha(areceipts) {
  583. t.Errorf("block #%d [%x]: receipts mismatch: have %v, want %v", num, hash, freceipts, areceipts)
  584. }
  585. }
  586. // Check that the canonical chains are the same between the databases
  587. for i := 0; i < len(blocks)+1; i++ {
  588. if fhash, ahash := GetCanonicalHash(fastDb, uint64(i)), GetCanonicalHash(archiveDb, uint64(i)); fhash != ahash {
  589. t.Errorf("block #%d: canonical hash mismatch: have %v, want %v", i, fhash, ahash)
  590. }
  591. }
  592. }
  593. // Tests that various import methods move the chain head pointers to the correct
  594. // positions.
  595. func TestLightVsFastVsFullChainHeads(t *testing.T) {
  596. // Configure and generate a sample block chain
  597. var (
  598. gendb, _ = ethdb.NewMemDatabase()
  599. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  600. address = crypto.PubkeyToAddress(key.PublicKey)
  601. funds = big.NewInt(1000000000)
  602. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{address: {Balance: funds}}}
  603. genesis = gspec.MustCommit(gendb)
  604. )
  605. height := uint64(1024)
  606. blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil)
  607. // Configure a subchain to roll back
  608. remove := []common.Hash{}
  609. for _, block := range blocks[height/2:] {
  610. remove = append(remove, block.Hash())
  611. }
  612. // Create a small assertion method to check the three heads
  613. assert := func(t *testing.T, kind string, chain *BlockChain, header uint64, fast uint64, block uint64) {
  614. if num := chain.CurrentBlock().NumberU64(); num != block {
  615. t.Errorf("%s head block mismatch: have #%v, want #%v", kind, num, block)
  616. }
  617. if num := chain.CurrentFastBlock().NumberU64(); num != fast {
  618. t.Errorf("%s head fast-block mismatch: have #%v, want #%v", kind, num, fast)
  619. }
  620. if num := chain.CurrentHeader().Number.Uint64(); num != header {
  621. t.Errorf("%s head header mismatch: have #%v, want #%v", kind, num, header)
  622. }
  623. }
  624. // Import the chain as an archive node and ensure all pointers are updated
  625. archiveDb, _ := ethdb.NewMemDatabase()
  626. gspec.MustCommit(archiveDb)
  627. archive, _ := NewBlockChain(archiveDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  628. if n, err := archive.InsertChain(blocks); err != nil {
  629. t.Fatalf("failed to process block %d: %v", n, err)
  630. }
  631. defer archive.Stop()
  632. assert(t, "archive", archive, height, height, height)
  633. archive.Rollback(remove)
  634. assert(t, "archive", archive, height/2, height/2, height/2)
  635. // Import the chain as a non-archive node and ensure all pointers are updated
  636. fastDb, _ := ethdb.NewMemDatabase()
  637. gspec.MustCommit(fastDb)
  638. fast, _ := NewBlockChain(fastDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  639. defer fast.Stop()
  640. headers := make([]*types.Header, len(blocks))
  641. for i, block := range blocks {
  642. headers[i] = block.Header()
  643. }
  644. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  645. t.Fatalf("failed to insert header %d: %v", n, err)
  646. }
  647. if n, err := fast.InsertReceiptChain(blocks, receipts); err != nil {
  648. t.Fatalf("failed to insert receipt %d: %v", n, err)
  649. }
  650. assert(t, "fast", fast, height, height, 0)
  651. fast.Rollback(remove)
  652. assert(t, "fast", fast, height/2, height/2, 0)
  653. // Import the chain as a light node and ensure all pointers are updated
  654. lightDb, _ := ethdb.NewMemDatabase()
  655. gspec.MustCommit(lightDb)
  656. light, _ := NewBlockChain(lightDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  657. if n, err := light.InsertHeaderChain(headers, 1); err != nil {
  658. t.Fatalf("failed to insert header %d: %v", n, err)
  659. }
  660. defer light.Stop()
  661. assert(t, "light", light, height, 0, 0)
  662. light.Rollback(remove)
  663. assert(t, "light", light, height/2, 0, 0)
  664. }
  665. // Tests that chain reorganisations handle transaction removals and reinsertions.
  666. func TestChainTxReorgs(t *testing.T) {
  667. var (
  668. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  669. key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  670. key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  671. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  672. addr2 = crypto.PubkeyToAddress(key2.PublicKey)
  673. addr3 = crypto.PubkeyToAddress(key3.PublicKey)
  674. db, _ = ethdb.NewMemDatabase()
  675. gspec = &Genesis{
  676. Config: params.TestChainConfig,
  677. GasLimit: 3141592,
  678. Alloc: GenesisAlloc{
  679. addr1: {Balance: big.NewInt(1000000)},
  680. addr2: {Balance: big.NewInt(1000000)},
  681. addr3: {Balance: big.NewInt(1000000)},
  682. },
  683. }
  684. genesis = gspec.MustCommit(db)
  685. signer = types.NewEIP155Signer(gspec.Config.ChainId)
  686. )
  687. // Create two transactions shared between the chains:
  688. // - postponed: transaction included at a later block in the forked chain
  689. // - swapped: transaction included at the same block number in the forked chain
  690. postponed, _ := types.SignTx(types.NewTransaction(0, addr1, big.NewInt(1000), params.TxGas, nil, nil), signer, key1)
  691. swapped, _ := types.SignTx(types.NewTransaction(1, addr1, big.NewInt(1000), params.TxGas, nil, nil), signer, key1)
  692. // Create two transactions that will be dropped by the forked chain:
  693. // - pastDrop: transaction dropped retroactively from a past block
  694. // - freshDrop: transaction dropped exactly at the block where the reorg is detected
  695. var pastDrop, freshDrop *types.Transaction
  696. // Create three transactions that will be added in the forked chain:
  697. // - pastAdd: transaction added before the reorganization is detected
  698. // - freshAdd: transaction added at the exact block the reorg is detected
  699. // - futureAdd: transaction added after the reorg has already finished
  700. var pastAdd, freshAdd, futureAdd *types.Transaction
  701. chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {
  702. switch i {
  703. case 0:
  704. pastDrop, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil), signer, key2)
  705. gen.AddTx(pastDrop) // This transaction will be dropped in the fork from below the split point
  706. gen.AddTx(postponed) // This transaction will be postponed till block #3 in the fork
  707. case 2:
  708. freshDrop, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil), signer, key2)
  709. gen.AddTx(freshDrop) // This transaction will be dropped in the fork from exactly at the split point
  710. gen.AddTx(swapped) // This transaction will be swapped out at the exact height
  711. gen.OffsetTime(9) // Lower the block difficulty to simulate a weaker chain
  712. }
  713. })
  714. // Import the chain. This runs all block validation rules.
  715. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  716. if i, err := blockchain.InsertChain(chain); err != nil {
  717. t.Fatalf("failed to insert original chain[%d]: %v", i, err)
  718. }
  719. defer blockchain.Stop()
  720. // overwrite the old chain
  721. chain, _ = GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 5, func(i int, gen *BlockGen) {
  722. switch i {
  723. case 0:
  724. pastAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key3)
  725. gen.AddTx(pastAdd) // This transaction needs to be injected during reorg
  726. case 2:
  727. gen.AddTx(postponed) // This transaction was postponed from block #1 in the original chain
  728. gen.AddTx(swapped) // This transaction was swapped from the exact current spot in the original chain
  729. freshAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key3)
  730. gen.AddTx(freshAdd) // This transaction will be added exactly at reorg time
  731. case 3:
  732. futureAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key3)
  733. gen.AddTx(futureAdd) // This transaction will be added after a full reorg
  734. }
  735. })
  736. if _, err := blockchain.InsertChain(chain); err != nil {
  737. t.Fatalf("failed to insert forked chain: %v", err)
  738. }
  739. // removed tx
  740. for i, tx := range (types.Transactions{pastDrop, freshDrop}) {
  741. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn != nil {
  742. t.Errorf("drop %d: tx %v found while shouldn't have been", i, txn)
  743. }
  744. if rcpt, _, _, _ := GetReceipt(db, tx.Hash()); rcpt != nil {
  745. t.Errorf("drop %d: receipt %v found while shouldn't have been", i, rcpt)
  746. }
  747. }
  748. // added tx
  749. for i, tx := range (types.Transactions{pastAdd, freshAdd, futureAdd}) {
  750. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn == nil {
  751. t.Errorf("add %d: expected tx to be found", i)
  752. }
  753. if rcpt, _, _, _ := GetReceipt(db, tx.Hash()); rcpt == nil {
  754. t.Errorf("add %d: expected receipt to be found", i)
  755. }
  756. }
  757. // shared tx
  758. for i, tx := range (types.Transactions{postponed, swapped}) {
  759. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn == nil {
  760. t.Errorf("share %d: expected tx to be found", i)
  761. }
  762. if rcpt, _, _, _ := GetReceipt(db, tx.Hash()); rcpt == nil {
  763. t.Errorf("share %d: expected receipt to be found", i)
  764. }
  765. }
  766. }
  767. func TestLogReorgs(t *testing.T) {
  768. var (
  769. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  770. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  771. db, _ = ethdb.NewMemDatabase()
  772. // this code generates a log
  773. code = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
  774. gspec = &Genesis{Config: params.TestChainConfig, Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}}}
  775. genesis = gspec.MustCommit(db)
  776. signer = types.NewEIP155Signer(gspec.Config.ChainId)
  777. )
  778. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  779. defer blockchain.Stop()
  780. rmLogsCh := make(chan RemovedLogsEvent)
  781. blockchain.SubscribeRemovedLogsEvent(rmLogsCh)
  782. chain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) {
  783. if i == 1 {
  784. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), code), signer, key1)
  785. if err != nil {
  786. t.Fatalf("failed to create tx: %v", err)
  787. }
  788. gen.AddTx(tx)
  789. }
  790. })
  791. if _, err := blockchain.InsertChain(chain); err != nil {
  792. t.Fatalf("failed to insert chain: %v", err)
  793. }
  794. chain, _ = GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {})
  795. if _, err := blockchain.InsertChain(chain); err != nil {
  796. t.Fatalf("failed to insert forked chain: %v", err)
  797. }
  798. timeout := time.NewTimer(1 * time.Second)
  799. select {
  800. case ev := <-rmLogsCh:
  801. if len(ev.Logs) == 0 {
  802. t.Error("expected logs")
  803. }
  804. case <-timeout.C:
  805. t.Fatal("Timeout. There is no RemovedLogsEvent has been sent.")
  806. }
  807. }
  808. func TestReorgSideEvent(t *testing.T) {
  809. var (
  810. db, _ = ethdb.NewMemDatabase()
  811. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  812. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  813. gspec = &Genesis{
  814. Config: params.TestChainConfig,
  815. Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000)}},
  816. }
  817. genesis = gspec.MustCommit(db)
  818. signer = types.NewEIP155Signer(gspec.Config.ChainId)
  819. )
  820. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  821. defer blockchain.Stop()
  822. chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {})
  823. if _, err := blockchain.InsertChain(chain); err != nil {
  824. t.Fatalf("failed to insert chain: %v", err)
  825. }
  826. replacementBlocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 4, func(i int, gen *BlockGen) {
  827. tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, new(big.Int), nil), signer, key1)
  828. if i == 2 {
  829. gen.OffsetTime(-9)
  830. }
  831. if err != nil {
  832. t.Fatalf("failed to create tx: %v", err)
  833. }
  834. gen.AddTx(tx)
  835. })
  836. chainSideCh := make(chan ChainSideEvent, 64)
  837. blockchain.SubscribeChainSideEvent(chainSideCh)
  838. if _, err := blockchain.InsertChain(replacementBlocks); err != nil {
  839. t.Fatalf("failed to insert chain: %v", err)
  840. }
  841. // first two block of the secondary chain are for a brief moment considered
  842. // side chains because up to that point the first one is considered the
  843. // heavier chain.
  844. expectedSideHashes := map[common.Hash]bool{
  845. replacementBlocks[0].Hash(): true,
  846. replacementBlocks[1].Hash(): true,
  847. chain[0].Hash(): true,
  848. chain[1].Hash(): true,
  849. chain[2].Hash(): true,
  850. }
  851. i := 0
  852. const timeoutDura = 10 * time.Second
  853. timeout := time.NewTimer(timeoutDura)
  854. done:
  855. for {
  856. select {
  857. case ev := <-chainSideCh:
  858. block := ev.Block
  859. if _, ok := expectedSideHashes[block.Hash()]; !ok {
  860. t.Errorf("%d: didn't expect %x to be in side chain", i, block.Hash())
  861. }
  862. i++
  863. if i == len(expectedSideHashes) {
  864. timeout.Stop()
  865. break done
  866. }
  867. timeout.Reset(timeoutDura)
  868. case <-timeout.C:
  869. t.Fatal("Timeout. Possibly not all blocks were triggered for sideevent")
  870. }
  871. }
  872. // make sure no more events are fired
  873. select {
  874. case e := <-chainSideCh:
  875. t.Errorf("unexpected event fired: %v", e)
  876. case <-time.After(250 * time.Millisecond):
  877. }
  878. }
  879. // Tests if the canonical block can be fetched from the database during chain insertion.
  880. func TestCanonicalBlockRetrieval(t *testing.T) {
  881. _, blockchain, err := newCanonical(ethash.NewFaker(), 0, true)
  882. if err != nil {
  883. t.Fatalf("failed to create pristine chain: %v", err)
  884. }
  885. defer blockchain.Stop()
  886. chain, _ := GenerateChain(blockchain.chainConfig, blockchain.genesisBlock, ethash.NewFaker(), blockchain.db, 10, func(i int, gen *BlockGen) {})
  887. var pend sync.WaitGroup
  888. pend.Add(len(chain))
  889. for i := range chain {
  890. go func(block *types.Block) {
  891. defer pend.Done()
  892. // try to retrieve a block by its canonical hash and see if the block data can be retrieved.
  893. for {
  894. ch := GetCanonicalHash(blockchain.db, block.NumberU64())
  895. if ch == (common.Hash{}) {
  896. continue // busy wait for canonical hash to be written
  897. }
  898. if ch != block.Hash() {
  899. t.Fatalf("unknown canonical hash, want %s, got %s", block.Hash().Hex(), ch.Hex())
  900. }
  901. fb := GetBlock(blockchain.db, ch, block.NumberU64())
  902. if fb == nil {
  903. t.Fatalf("unable to retrieve block %d for canonical hash: %s", block.NumberU64(), ch.Hex())
  904. }
  905. if fb.Hash() != block.Hash() {
  906. t.Fatalf("invalid block hash for block %d, want %s, got %s", block.NumberU64(), block.Hash().Hex(), fb.Hash().Hex())
  907. }
  908. return
  909. }
  910. }(chain[i])
  911. if _, err := blockchain.InsertChain(types.Blocks{chain[i]}); err != nil {
  912. t.Fatalf("failed to insert block %d: %v", i, err)
  913. }
  914. }
  915. pend.Wait()
  916. }
  917. func TestEIP155Transition(t *testing.T) {
  918. // Configure and generate a sample block chain
  919. var (
  920. db, _ = ethdb.NewMemDatabase()
  921. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  922. address = crypto.PubkeyToAddress(key.PublicKey)
  923. funds = big.NewInt(1000000000)
  924. deleteAddr = common.Address{1}
  925. gspec = &Genesis{
  926. Config: &params.ChainConfig{ChainId: big.NewInt(1), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)},
  927. Alloc: GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}},
  928. }
  929. genesis = gspec.MustCommit(db)
  930. )
  931. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  932. defer blockchain.Stop()
  933. blocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 4, func(i int, block *BlockGen) {
  934. var (
  935. tx *types.Transaction
  936. err error
  937. basicTx = func(signer types.Signer) (*types.Transaction, error) {
  938. return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(big.Int), 21000, new(big.Int), nil), signer, key)
  939. }
  940. )
  941. switch i {
  942. case 0:
  943. tx, err = basicTx(types.HomesteadSigner{})
  944. if err != nil {
  945. t.Fatal(err)
  946. }
  947. block.AddTx(tx)
  948. case 2:
  949. tx, err = basicTx(types.HomesteadSigner{})
  950. if err != nil {
  951. t.Fatal(err)
  952. }
  953. block.AddTx(tx)
  954. tx, err = basicTx(types.NewEIP155Signer(gspec.Config.ChainId))
  955. if err != nil {
  956. t.Fatal(err)
  957. }
  958. block.AddTx(tx)
  959. case 3:
  960. tx, err = basicTx(types.HomesteadSigner{})
  961. if err != nil {
  962. t.Fatal(err)
  963. }
  964. block.AddTx(tx)
  965. tx, err = basicTx(types.NewEIP155Signer(gspec.Config.ChainId))
  966. if err != nil {
  967. t.Fatal(err)
  968. }
  969. block.AddTx(tx)
  970. }
  971. })
  972. if _, err := blockchain.InsertChain(blocks); err != nil {
  973. t.Fatal(err)
  974. }
  975. block := blockchain.GetBlockByNumber(1)
  976. if block.Transactions()[0].Protected() {
  977. t.Error("Expected block[0].txs[0] to not be replay protected")
  978. }
  979. block = blockchain.GetBlockByNumber(3)
  980. if block.Transactions()[0].Protected() {
  981. t.Error("Expected block[3].txs[0] to not be replay protected")
  982. }
  983. if !block.Transactions()[1].Protected() {
  984. t.Error("Expected block[3].txs[1] to be replay protected")
  985. }
  986. if _, err := blockchain.InsertChain(blocks[4:]); err != nil {
  987. t.Fatal(err)
  988. }
  989. // generate an invalid chain id transaction
  990. config := &params.ChainConfig{ChainId: big.NewInt(2), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)}
  991. blocks, _ = GenerateChain(config, blocks[len(blocks)-1], ethash.NewFaker(), db, 4, func(i int, block *BlockGen) {
  992. var (
  993. tx *types.Transaction
  994. err error
  995. basicTx = func(signer types.Signer) (*types.Transaction, error) {
  996. return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(big.Int), 21000, new(big.Int), nil), signer, key)
  997. }
  998. )
  999. switch i {
  1000. case 0:
  1001. tx, err = basicTx(types.NewEIP155Signer(big.NewInt(2)))
  1002. if err != nil {
  1003. t.Fatal(err)
  1004. }
  1005. block.AddTx(tx)
  1006. }
  1007. })
  1008. _, err := blockchain.InsertChain(blocks)
  1009. if err != types.ErrInvalidChainId {
  1010. t.Error("expected error:", types.ErrInvalidChainId)
  1011. }
  1012. }
  1013. func TestEIP161AccountRemoval(t *testing.T) {
  1014. // Configure and generate a sample block chain
  1015. var (
  1016. db, _ = ethdb.NewMemDatabase()
  1017. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  1018. address = crypto.PubkeyToAddress(key.PublicKey)
  1019. funds = big.NewInt(1000000000)
  1020. theAddr = common.Address{1}
  1021. gspec = &Genesis{
  1022. Config: &params.ChainConfig{
  1023. ChainId: big.NewInt(1),
  1024. HomesteadBlock: new(big.Int),
  1025. EIP155Block: new(big.Int),
  1026. EIP158Block: big.NewInt(2),
  1027. },
  1028. Alloc: GenesisAlloc{address: {Balance: funds}},
  1029. }
  1030. genesis = gspec.MustCommit(db)
  1031. )
  1032. blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{})
  1033. defer blockchain.Stop()
  1034. blocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, block *BlockGen) {
  1035. var (
  1036. tx *types.Transaction
  1037. err error
  1038. signer = types.NewEIP155Signer(gspec.Config.ChainId)
  1039. )
  1040. switch i {
  1041. case 0:
  1042. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1043. case 1:
  1044. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1045. case 2:
  1046. tx, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr, new(big.Int), 21000, new(big.Int), nil), signer, key)
  1047. }
  1048. if err != nil {
  1049. t.Fatal(err)
  1050. }
  1051. block.AddTx(tx)
  1052. })
  1053. // account must exist pre eip 161
  1054. if _, err := blockchain.InsertChain(types.Blocks{blocks[0]}); err != nil {
  1055. t.Fatal(err)
  1056. }
  1057. if st, _ := blockchain.State(); !st.Exist(theAddr) {
  1058. t.Error("expected account to exist")
  1059. }
  1060. // account needs to be deleted post eip 161
  1061. if _, err := blockchain.InsertChain(types.Blocks{blocks[1]}); err != nil {
  1062. t.Fatal(err)
  1063. }
  1064. if st, _ := blockchain.State(); st.Exist(theAddr) {
  1065. t.Error("account should not exist")
  1066. }
  1067. // account musn't be created post eip 161
  1068. if _, err := blockchain.InsertChain(types.Blocks{blocks[2]}); err != nil {
  1069. t.Fatal(err)
  1070. }
  1071. if st, _ := blockchain.State(); st.Exist(theAddr) {
  1072. t.Error("account should not exist")
  1073. }
  1074. }
  1075. // This is a regression test (i.e. as weird as it is, don't delete it ever), which
  1076. // tests that under weird reorg conditions the blockchain and its internal header-
  1077. // chain return the same latest block/header.
  1078. //
  1079. // https://github.com/ethereum/go-ethereum/pull/15941
  1080. func TestBlockchainHeaderchainReorgConsistency(t *testing.T) {
  1081. // Generate a canonical chain to act as the main dataset
  1082. engine := ethash.NewFaker()
  1083. db, _ := ethdb.NewMemDatabase()
  1084. genesis := new(Genesis).MustCommit(db)
  1085. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1086. // Generate a bunch of fork blocks, each side forking from the canonical chain
  1087. forks := make([]*types.Block, len(blocks))
  1088. for i := 0; i < len(forks); i++ {
  1089. parent := genesis
  1090. if i > 0 {
  1091. parent = blocks[i-1]
  1092. }
  1093. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1094. forks[i] = fork[0]
  1095. }
  1096. // Import the canonical and fork chain side by side, verifying the current block
  1097. // and current header consistency
  1098. diskdb, _ := ethdb.NewMemDatabase()
  1099. new(Genesis).MustCommit(diskdb)
  1100. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{})
  1101. if err != nil {
  1102. t.Fatalf("failed to create tester chain: %v", err)
  1103. }
  1104. for i := 0; i < len(blocks); i++ {
  1105. if _, err := chain.InsertChain(blocks[i : i+1]); err != nil {
  1106. t.Fatalf("block %d: failed to insert into chain: %v", i, err)
  1107. }
  1108. if chain.CurrentBlock().Hash() != chain.CurrentHeader().Hash() {
  1109. 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])
  1110. }
  1111. if _, err := chain.InsertChain(forks[i : i+1]); err != nil {
  1112. t.Fatalf(" fork %d: failed to insert into chain: %v", i, err)
  1113. }
  1114. if chain.CurrentBlock().Hash() != chain.CurrentHeader().Hash() {
  1115. 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])
  1116. }
  1117. }
  1118. }
  1119. // Tests that importing small side forks doesn't leave junk in the trie database
  1120. // cache (which would eventually cause memory issues).
  1121. func TestTrieForkGC(t *testing.T) {
  1122. // Generate a canonical chain to act as the main dataset
  1123. engine := ethash.NewFaker()
  1124. db, _ := ethdb.NewMemDatabase()
  1125. genesis := new(Genesis).MustCommit(db)
  1126. blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 2*triesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1127. // Generate a bunch of fork blocks, each side forking from the canonical chain
  1128. forks := make([]*types.Block, len(blocks))
  1129. for i := 0; i < len(forks); i++ {
  1130. parent := genesis
  1131. if i > 0 {
  1132. parent = blocks[i-1]
  1133. }
  1134. fork, _ := GenerateChain(params.TestChainConfig, parent, engine, db, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1135. forks[i] = fork[0]
  1136. }
  1137. // Import the canonical and fork chain side by side, forcing the trie cache to cache both
  1138. diskdb, _ := ethdb.NewMemDatabase()
  1139. new(Genesis).MustCommit(diskdb)
  1140. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{})
  1141. if err != nil {
  1142. t.Fatalf("failed to create tester chain: %v", err)
  1143. }
  1144. for i := 0; i < len(blocks); i++ {
  1145. if _, err := chain.InsertChain(blocks[i : i+1]); err != nil {
  1146. t.Fatalf("block %d: failed to insert into chain: %v", i, err)
  1147. }
  1148. if _, err := chain.InsertChain(forks[i : i+1]); err != nil {
  1149. t.Fatalf("fork %d: failed to insert into chain: %v", i, err)
  1150. }
  1151. }
  1152. // Dereference all the recent tries and ensure no past trie is left in
  1153. for i := 0; i < triesInMemory; i++ {
  1154. chain.stateCache.TrieDB().Dereference(blocks[len(blocks)-1-i].Root(), common.Hash{})
  1155. chain.stateCache.TrieDB().Dereference(forks[len(blocks)-1-i].Root(), common.Hash{})
  1156. }
  1157. if len(chain.stateCache.TrieDB().Nodes()) > 0 {
  1158. t.Fatalf("stale tries still alive after garbase collection")
  1159. }
  1160. }
  1161. // Tests that doing large reorgs works even if the state associated with the
  1162. // forking point is not available any more.
  1163. func TestLargeReorgTrieGC(t *testing.T) {
  1164. // Generate the original common chain segment and the two competing forks
  1165. engine := ethash.NewFaker()
  1166. db, _ := ethdb.NewMemDatabase()
  1167. genesis := new(Genesis).MustCommit(db)
  1168. shared, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) })
  1169. original, _ := GenerateChain(params.TestChainConfig, shared[len(shared)-1], engine, db, 2*triesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) })
  1170. competitor, _ := GenerateChain(params.TestChainConfig, shared[len(shared)-1], engine, db, 2*triesInMemory+1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{3}) })
  1171. // Import the shared chain and the original canonical one
  1172. diskdb, _ := ethdb.NewMemDatabase()
  1173. new(Genesis).MustCommit(diskdb)
  1174. chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{})
  1175. if err != nil {
  1176. t.Fatalf("failed to create tester chain: %v", err)
  1177. }
  1178. if _, err := chain.InsertChain(shared); err != nil {
  1179. t.Fatalf("failed to insert shared chain: %v", err)
  1180. }
  1181. if _, err := chain.InsertChain(original); err != nil {
  1182. t.Fatalf("failed to insert shared chain: %v", err)
  1183. }
  1184. // Ensure that the state associated with the forking point is pruned away
  1185. if node, _ := chain.stateCache.TrieDB().Node(shared[len(shared)-1].Root()); node != nil {
  1186. t.Fatalf("common-but-old ancestor still cache")
  1187. }
  1188. // Import the competitor chain without exceeding the canonical's TD and ensure
  1189. // we have not processed any of the blocks (protection against malicious blocks)
  1190. if _, err := chain.InsertChain(competitor[:len(competitor)-2]); err != nil {
  1191. t.Fatalf("failed to insert competitor chain: %v", err)
  1192. }
  1193. for i, block := range competitor[:len(competitor)-2] {
  1194. if node, _ := chain.stateCache.TrieDB().Node(block.Root()); node != nil {
  1195. t.Fatalf("competitor %d: low TD chain became processed", i)
  1196. }
  1197. }
  1198. // Import the head of the competitor chain, triggering the reorg and ensure we
  1199. // successfully reprocess all the stashed away blocks.
  1200. if _, err := chain.InsertChain(competitor[len(competitor)-2:]); err != nil {
  1201. t.Fatalf("failed to finalize competitor chain: %v", err)
  1202. }
  1203. for i, block := range competitor[:len(competitor)-triesInMemory] {
  1204. if node, _ := chain.stateCache.TrieDB().Node(block.Root()); node != nil {
  1205. t.Fatalf("competitor %d: competing chain state missing", i)
  1206. }
  1207. }
  1208. }