blockchain_test.go 43 KB

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