blockchain_test.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. "os"
  22. "path/filepath"
  23. "runtime"
  24. "strconv"
  25. "testing"
  26. "github.com/ethereum/ethash"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/core/vm"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/ethdb"
  33. "github.com/ethereum/go-ethereum/event"
  34. "github.com/ethereum/go-ethereum/params"
  35. "github.com/ethereum/go-ethereum/pow"
  36. "github.com/ethereum/go-ethereum/rlp"
  37. "github.com/hashicorp/golang-lru"
  38. )
  39. func init() {
  40. runtime.GOMAXPROCS(runtime.NumCPU())
  41. }
  42. func thePow() pow.PoW {
  43. pow, _ := ethash.NewForTesting()
  44. return pow
  45. }
  46. func theBlockChain(db ethdb.Database, t *testing.T) *BlockChain {
  47. var eventMux event.TypeMux
  48. WriteTestNetGenesisBlock(db)
  49. blockchain, err := NewBlockChain(db, thePow(), &eventMux)
  50. if err != nil {
  51. t.Error("failed creating blockchain:", err)
  52. t.FailNow()
  53. return nil
  54. }
  55. return blockchain
  56. }
  57. // Test fork of length N starting from block i
  58. func testFork(t *testing.T, blockchain *BlockChain, i, n int, full bool, comparator func(td1, td2 *big.Int)) {
  59. // Copy old chain up to #i into a new db
  60. db, blockchain2, err := newCanonical(i, full)
  61. if err != nil {
  62. t.Fatal("could not make new canonical in testFork", err)
  63. }
  64. // Assert the chains have the same header/block at #i
  65. var hash1, hash2 common.Hash
  66. if full {
  67. hash1 = blockchain.GetBlockByNumber(uint64(i)).Hash()
  68. hash2 = blockchain2.GetBlockByNumber(uint64(i)).Hash()
  69. } else {
  70. hash1 = blockchain.GetHeaderByNumber(uint64(i)).Hash()
  71. hash2 = blockchain2.GetHeaderByNumber(uint64(i)).Hash()
  72. }
  73. if hash1 != hash2 {
  74. t.Errorf("chain content mismatch at %d: have hash %v, want hash %v", i, hash2, hash1)
  75. }
  76. // Extend the newly created chain
  77. var (
  78. blockChainB []*types.Block
  79. headerChainB []*types.Header
  80. )
  81. if full {
  82. blockChainB = makeBlockChain(blockchain2.CurrentBlock(), n, db, forkSeed)
  83. if _, err := blockchain2.InsertChain(blockChainB); err != nil {
  84. t.Fatalf("failed to insert forking chain: %v", err)
  85. }
  86. } else {
  87. headerChainB = makeHeaderChain(blockchain2.CurrentHeader(), n, db, forkSeed)
  88. if _, err := blockchain2.InsertHeaderChain(headerChainB, 1); err != nil {
  89. t.Fatalf("failed to insert forking chain: %v", err)
  90. }
  91. }
  92. // Sanity check that the forked chain can be imported into the original
  93. var tdPre, tdPost *big.Int
  94. if full {
  95. tdPre = blockchain.GetTd(blockchain.CurrentBlock().Hash())
  96. if err := testBlockChainImport(blockChainB, blockchain); err != nil {
  97. t.Fatalf("failed to import forked block chain: %v", err)
  98. }
  99. tdPost = blockchain.GetTd(blockChainB[len(blockChainB)-1].Hash())
  100. } else {
  101. tdPre = blockchain.GetTd(blockchain.CurrentHeader().Hash())
  102. if err := testHeaderChainImport(headerChainB, blockchain); err != nil {
  103. t.Fatalf("failed to import forked header chain: %v", err)
  104. }
  105. tdPost = blockchain.GetTd(headerChainB[len(headerChainB)-1].Hash())
  106. }
  107. // Compare the total difficulties of the chains
  108. comparator(tdPre, tdPost)
  109. }
  110. func printChain(bc *BlockChain) {
  111. for i := bc.CurrentBlock().Number().Uint64(); i > 0; i-- {
  112. b := bc.GetBlockByNumber(uint64(i))
  113. fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty())
  114. }
  115. }
  116. // testBlockChainImport tries to process a chain of blocks, writing them into
  117. // the database if successful.
  118. func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error {
  119. for _, block := range chain {
  120. // Try and process the block
  121. err := blockchain.Validator().ValidateBlock(block)
  122. if err != nil {
  123. if IsKnownBlockErr(err) {
  124. continue
  125. }
  126. return err
  127. }
  128. statedb, err := state.New(blockchain.GetBlock(block.ParentHash()).Root(), blockchain.chainDb)
  129. if err != nil {
  130. return err
  131. }
  132. receipts, _, usedGas, err := blockchain.Processor().Process(block, statedb)
  133. if err != nil {
  134. reportBlock(block, err)
  135. return err
  136. }
  137. err = blockchain.Validator().ValidateState(block, blockchain.GetBlock(block.ParentHash()), statedb, receipts, usedGas)
  138. if err != nil {
  139. reportBlock(block, err)
  140. return err
  141. }
  142. blockchain.mu.Lock()
  143. WriteTd(blockchain.chainDb, block.Hash(), new(big.Int).Add(block.Difficulty(), blockchain.GetTd(block.ParentHash())))
  144. WriteBlock(blockchain.chainDb, block)
  145. statedb.Commit()
  146. blockchain.mu.Unlock()
  147. }
  148. return nil
  149. }
  150. // testHeaderChainImport tries to process a chain of header, writing them into
  151. // the database if successful.
  152. func testHeaderChainImport(chain []*types.Header, blockchain *BlockChain) error {
  153. for _, header := range chain {
  154. // Try and validate the header
  155. if err := blockchain.Validator().ValidateHeader(header, blockchain.GetHeader(header.ParentHash), false); err != nil {
  156. return err
  157. }
  158. // Manually insert the header into the database, but don't reorganize (allows subsequent testing)
  159. blockchain.mu.Lock()
  160. WriteTd(blockchain.chainDb, header.Hash(), new(big.Int).Add(header.Difficulty, blockchain.GetTd(header.ParentHash)))
  161. WriteHeader(blockchain.chainDb, header)
  162. blockchain.mu.Unlock()
  163. }
  164. return nil
  165. }
  166. func loadChain(fn string, t *testing.T) (types.Blocks, error) {
  167. fh, err := os.OpenFile(filepath.Join("..", "_data", fn), os.O_RDONLY, os.ModePerm)
  168. if err != nil {
  169. return nil, err
  170. }
  171. defer fh.Close()
  172. var chain types.Blocks
  173. if err := rlp.Decode(fh, &chain); err != nil {
  174. return nil, err
  175. }
  176. return chain, nil
  177. }
  178. func insertChain(done chan bool, blockchain *BlockChain, chain types.Blocks, t *testing.T) {
  179. _, err := blockchain.InsertChain(chain)
  180. if err != nil {
  181. fmt.Println(err)
  182. t.FailNow()
  183. }
  184. done <- true
  185. }
  186. func TestLastBlock(t *testing.T) {
  187. db, _ := ethdb.NewMemDatabase()
  188. bchain := theBlockChain(db, t)
  189. block := makeBlockChain(bchain.CurrentBlock(), 1, db, 0)[0]
  190. bchain.insert(block)
  191. if block.Hash() != GetHeadBlockHash(db) {
  192. t.Errorf("Write/Get HeadBlockHash failed")
  193. }
  194. }
  195. // Tests that given a starting canonical chain of a given size, it can be extended
  196. // with various length chains.
  197. func TestExtendCanonicalHeaders(t *testing.T) { testExtendCanonical(t, false) }
  198. func TestExtendCanonicalBlocks(t *testing.T) { testExtendCanonical(t, true) }
  199. func testExtendCanonical(t *testing.T, full bool) {
  200. length := 5
  201. // Make first chain starting from genesis
  202. _, processor, err := newCanonical(length, full)
  203. if err != nil {
  204. t.Fatalf("failed to make new canonical chain: %v", err)
  205. }
  206. // Define the difficulty comparator
  207. better := func(td1, td2 *big.Int) {
  208. if td2.Cmp(td1) <= 0 {
  209. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  210. }
  211. }
  212. // Start fork from current height
  213. testFork(t, processor, length, 1, full, better)
  214. testFork(t, processor, length, 2, full, better)
  215. testFork(t, processor, length, 5, full, better)
  216. testFork(t, processor, length, 10, full, better)
  217. }
  218. // Tests that given a starting canonical chain of a given size, creating shorter
  219. // forks do not take canonical ownership.
  220. func TestShorterForkHeaders(t *testing.T) { testShorterFork(t, false) }
  221. func TestShorterForkBlocks(t *testing.T) { testShorterFork(t, true) }
  222. func testShorterFork(t *testing.T, full bool) {
  223. length := 10
  224. // Make first chain starting from genesis
  225. _, processor, err := newCanonical(length, full)
  226. if err != nil {
  227. t.Fatalf("failed to make new canonical chain: %v", err)
  228. }
  229. // Define the difficulty comparator
  230. worse := func(td1, td2 *big.Int) {
  231. if td2.Cmp(td1) >= 0 {
  232. t.Errorf("total difficulty mismatch: have %v, expected less than %v", td2, td1)
  233. }
  234. }
  235. // Sum of numbers must be less than `length` for this to be a shorter fork
  236. testFork(t, processor, 0, 3, full, worse)
  237. testFork(t, processor, 0, 7, full, worse)
  238. testFork(t, processor, 1, 1, full, worse)
  239. testFork(t, processor, 1, 7, full, worse)
  240. testFork(t, processor, 5, 3, full, worse)
  241. testFork(t, processor, 5, 4, full, worse)
  242. }
  243. // Tests that given a starting canonical chain of a given size, creating longer
  244. // forks do take canonical ownership.
  245. func TestLongerForkHeaders(t *testing.T) { testLongerFork(t, false) }
  246. func TestLongerForkBlocks(t *testing.T) { testLongerFork(t, true) }
  247. func testLongerFork(t *testing.T, full bool) {
  248. length := 10
  249. // Make first chain starting from genesis
  250. _, processor, err := newCanonical(length, full)
  251. if err != nil {
  252. t.Fatalf("failed to make new canonical chain: %v", err)
  253. }
  254. // Define the difficulty comparator
  255. better := func(td1, td2 *big.Int) {
  256. if td2.Cmp(td1) <= 0 {
  257. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  258. }
  259. }
  260. // Sum of numbers must be greater than `length` for this to be a longer fork
  261. testFork(t, processor, 0, 11, full, better)
  262. testFork(t, processor, 0, 15, full, better)
  263. testFork(t, processor, 1, 10, full, better)
  264. testFork(t, processor, 1, 12, full, better)
  265. testFork(t, processor, 5, 6, full, better)
  266. testFork(t, processor, 5, 8, full, better)
  267. }
  268. // Tests that given a starting canonical chain of a given size, creating equal
  269. // forks do take canonical ownership.
  270. func TestEqualForkHeaders(t *testing.T) { testEqualFork(t, false) }
  271. func TestEqualForkBlocks(t *testing.T) { testEqualFork(t, true) }
  272. func testEqualFork(t *testing.T, full bool) {
  273. length := 10
  274. // Make first chain starting from genesis
  275. _, processor, err := newCanonical(length, full)
  276. if err != nil {
  277. t.Fatalf("failed to make new canonical chain: %v", err)
  278. }
  279. // Define the difficulty comparator
  280. equal := func(td1, td2 *big.Int) {
  281. if td2.Cmp(td1) != 0 {
  282. t.Errorf("total difficulty mismatch: have %v, want %v", td2, td1)
  283. }
  284. }
  285. // Sum of numbers must be equal to `length` for this to be an equal fork
  286. testFork(t, processor, 0, 10, full, equal)
  287. testFork(t, processor, 1, 9, full, equal)
  288. testFork(t, processor, 2, 8, full, equal)
  289. testFork(t, processor, 5, 5, full, equal)
  290. testFork(t, processor, 6, 4, full, equal)
  291. testFork(t, processor, 9, 1, full, equal)
  292. }
  293. // Tests that chains missing links do not get accepted by the processor.
  294. func TestBrokenHeaderChain(t *testing.T) { testBrokenChain(t, false) }
  295. func TestBrokenBlockChain(t *testing.T) { testBrokenChain(t, true) }
  296. func testBrokenChain(t *testing.T, full bool) {
  297. // Make chain starting from genesis
  298. db, blockchain, err := newCanonical(10, full)
  299. if err != nil {
  300. t.Fatalf("failed to make new canonical chain: %v", err)
  301. }
  302. // Create a forked chain, and try to insert with a missing link
  303. if full {
  304. chain := makeBlockChain(blockchain.CurrentBlock(), 5, db, forkSeed)[1:]
  305. if err := testBlockChainImport(chain, blockchain); err == nil {
  306. t.Errorf("broken block chain not reported")
  307. }
  308. } else {
  309. chain := makeHeaderChain(blockchain.CurrentHeader(), 5, db, forkSeed)[1:]
  310. if err := testHeaderChainImport(chain, blockchain); err == nil {
  311. t.Errorf("broken header chain not reported")
  312. }
  313. }
  314. }
  315. func TestChainInsertions(t *testing.T) {
  316. t.Skip("Skipped: outdated test files")
  317. db, _ := ethdb.NewMemDatabase()
  318. chain1, err := loadChain("valid1", t)
  319. if err != nil {
  320. fmt.Println(err)
  321. t.FailNow()
  322. }
  323. chain2, err := loadChain("valid2", t)
  324. if err != nil {
  325. fmt.Println(err)
  326. t.FailNow()
  327. }
  328. blockchain := theBlockChain(db, t)
  329. const max = 2
  330. done := make(chan bool, max)
  331. go insertChain(done, blockchain, chain1, t)
  332. go insertChain(done, blockchain, chain2, t)
  333. for i := 0; i < max; i++ {
  334. <-done
  335. }
  336. if chain2[len(chain2)-1].Hash() != blockchain.CurrentBlock().Hash() {
  337. t.Error("chain2 is canonical and shouldn't be")
  338. }
  339. if chain1[len(chain1)-1].Hash() != blockchain.CurrentBlock().Hash() {
  340. t.Error("chain1 isn't canonical and should be")
  341. }
  342. }
  343. func TestChainMultipleInsertions(t *testing.T) {
  344. t.Skip("Skipped: outdated test files")
  345. db, _ := ethdb.NewMemDatabase()
  346. const max = 4
  347. chains := make([]types.Blocks, max)
  348. var longest int
  349. for i := 0; i < max; i++ {
  350. var err error
  351. name := "valid" + strconv.Itoa(i+1)
  352. chains[i], err = loadChain(name, t)
  353. if len(chains[i]) >= len(chains[longest]) {
  354. longest = i
  355. }
  356. fmt.Println("loaded", name, "with a length of", len(chains[i]))
  357. if err != nil {
  358. fmt.Println(err)
  359. t.FailNow()
  360. }
  361. }
  362. blockchain := theBlockChain(db, t)
  363. done := make(chan bool, max)
  364. for i, chain := range chains {
  365. // XXX the go routine would otherwise reference the same (chain[3]) variable and fail
  366. i := i
  367. chain := chain
  368. go func() {
  369. insertChain(done, blockchain, chain, t)
  370. fmt.Println(i, "done")
  371. }()
  372. }
  373. for i := 0; i < max; i++ {
  374. <-done
  375. }
  376. if chains[longest][len(chains[longest])-1].Hash() != blockchain.CurrentBlock().Hash() {
  377. t.Error("Invalid canonical chain")
  378. }
  379. }
  380. type bproc struct{}
  381. func (bproc) ValidateBlock(*types.Block) error { return nil }
  382. func (bproc) ValidateHeader(*types.Header, *types.Header, bool) error { return nil }
  383. func (bproc) ValidateState(block, parent *types.Block, state *state.StateDB, receipts types.Receipts, usedGas *big.Int) error {
  384. return nil
  385. }
  386. func (bproc) Process(block *types.Block, statedb *state.StateDB) (types.Receipts, vm.Logs, *big.Int, error) {
  387. return nil, nil, nil, nil
  388. }
  389. func makeHeaderChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Header {
  390. blocks := makeBlockChainWithDiff(genesis, d, seed)
  391. headers := make([]*types.Header, len(blocks))
  392. for i, block := range blocks {
  393. headers[i] = block.Header()
  394. }
  395. return headers
  396. }
  397. func makeBlockChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Block {
  398. var chain []*types.Block
  399. for i, difficulty := range d {
  400. header := &types.Header{
  401. Coinbase: common.Address{seed},
  402. Number: big.NewInt(int64(i + 1)),
  403. Difficulty: big.NewInt(int64(difficulty)),
  404. UncleHash: types.EmptyUncleHash,
  405. TxHash: types.EmptyRootHash,
  406. ReceiptHash: types.EmptyRootHash,
  407. }
  408. if i == 0 {
  409. header.ParentHash = genesis.Hash()
  410. } else {
  411. header.ParentHash = chain[i-1].Hash()
  412. }
  413. block := types.NewBlockWithHeader(header)
  414. chain = append(chain, block)
  415. }
  416. return chain
  417. }
  418. func chm(genesis *types.Block, db ethdb.Database) *BlockChain {
  419. var eventMux event.TypeMux
  420. bc := &BlockChain{chainDb: db, genesisBlock: genesis, eventMux: &eventMux, pow: FakePow{}, rand: rand.New(rand.NewSource(0))}
  421. bc.headerCache, _ = lru.New(100)
  422. bc.bodyCache, _ = lru.New(100)
  423. bc.bodyRLPCache, _ = lru.New(100)
  424. bc.tdCache, _ = lru.New(100)
  425. bc.blockCache, _ = lru.New(100)
  426. bc.futureBlocks, _ = lru.New(100)
  427. bc.SetValidator(bproc{})
  428. bc.SetProcessor(bproc{})
  429. bc.ResetWithGenesisBlock(genesis)
  430. return bc
  431. }
  432. // Tests that reorganizing a long difficult chain after a short easy one
  433. // overwrites the canonical numbers and links in the database.
  434. func TestReorgLongHeaders(t *testing.T) { testReorgLong(t, false) }
  435. func TestReorgLongBlocks(t *testing.T) { testReorgLong(t, true) }
  436. func testReorgLong(t *testing.T, full bool) {
  437. testReorg(t, []int{1, 2, 4}, []int{1, 2, 3, 4}, 10, full)
  438. }
  439. // Tests that reorganizing a short difficult chain after a long easy one
  440. // overwrites the canonical numbers and links in the database.
  441. func TestReorgShortHeaders(t *testing.T) { testReorgShort(t, false) }
  442. func TestReorgShortBlocks(t *testing.T) { testReorgShort(t, true) }
  443. func testReorgShort(t *testing.T, full bool) {
  444. testReorg(t, []int{1, 2, 3, 4}, []int{1, 10}, 11, full)
  445. }
  446. func testReorg(t *testing.T, first, second []int, td int64, full bool) {
  447. // Create a pristine block chain
  448. db, _ := ethdb.NewMemDatabase()
  449. genesis, _ := WriteTestNetGenesisBlock(db)
  450. bc := chm(genesis, db)
  451. // Insert an easy and a difficult chain afterwards
  452. if full {
  453. bc.InsertChain(makeBlockChainWithDiff(genesis, first, 11))
  454. bc.InsertChain(makeBlockChainWithDiff(genesis, second, 22))
  455. } else {
  456. bc.InsertHeaderChain(makeHeaderChainWithDiff(genesis, first, 11), 1)
  457. bc.InsertHeaderChain(makeHeaderChainWithDiff(genesis, second, 22), 1)
  458. }
  459. // Check that the chain is valid number and link wise
  460. if full {
  461. prev := bc.CurrentBlock()
  462. for block := bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 1); block.NumberU64() != 0; prev, block = block, bc.GetBlockByNumber(block.NumberU64()-1) {
  463. if prev.ParentHash() != block.Hash() {
  464. t.Errorf("parent block hash mismatch: have %x, want %x", prev.ParentHash(), block.Hash())
  465. }
  466. }
  467. } else {
  468. prev := bc.CurrentHeader()
  469. for header := bc.GetHeaderByNumber(bc.CurrentHeader().Number.Uint64() - 1); header.Number.Uint64() != 0; prev, header = header, bc.GetHeaderByNumber(header.Number.Uint64()-1) {
  470. if prev.ParentHash != header.Hash() {
  471. t.Errorf("parent header hash mismatch: have %x, want %x", prev.ParentHash, header.Hash())
  472. }
  473. }
  474. }
  475. // Make sure the chain total difficulty is the correct one
  476. want := new(big.Int).Add(genesis.Difficulty(), big.NewInt(td))
  477. if full {
  478. if have := bc.GetTd(bc.CurrentBlock().Hash()); have.Cmp(want) != 0 {
  479. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  480. }
  481. } else {
  482. if have := bc.GetTd(bc.CurrentHeader().Hash()); have.Cmp(want) != 0 {
  483. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  484. }
  485. }
  486. }
  487. // Tests that the insertion functions detect banned hashes.
  488. func TestBadHeaderHashes(t *testing.T) { testBadHashes(t, false) }
  489. func TestBadBlockHashes(t *testing.T) { testBadHashes(t, true) }
  490. func testBadHashes(t *testing.T, full bool) {
  491. // Create a pristine block chain
  492. db, _ := ethdb.NewMemDatabase()
  493. genesis, _ := WriteTestNetGenesisBlock(db)
  494. bc := chm(genesis, db)
  495. // Create a chain, ban a hash and try to import
  496. var err error
  497. if full {
  498. blocks := makeBlockChainWithDiff(genesis, []int{1, 2, 4}, 10)
  499. BadHashes[blocks[2].Header().Hash()] = true
  500. _, err = bc.InsertChain(blocks)
  501. } else {
  502. headers := makeHeaderChainWithDiff(genesis, []int{1, 2, 4}, 10)
  503. BadHashes[headers[2].Hash()] = true
  504. _, err = bc.InsertHeaderChain(headers, 1)
  505. }
  506. if !IsBadHashError(err) {
  507. t.Errorf("error mismatch: want: BadHashError, have: %v", err)
  508. }
  509. }
  510. // Tests that bad hashes are detected on boot, and the chan rolled back to a
  511. // good state prior to the bad hash.
  512. func TestReorgBadHeaderHashes(t *testing.T) { testReorgBadHashes(t, false) }
  513. func TestReorgBadBlockHashes(t *testing.T) { testReorgBadHashes(t, true) }
  514. func testReorgBadHashes(t *testing.T, full bool) {
  515. // Create a pristine block chain
  516. db, _ := ethdb.NewMemDatabase()
  517. genesis, _ := WriteTestNetGenesisBlock(db)
  518. bc := chm(genesis, db)
  519. // Create a chain, import and ban aferwards
  520. headers := makeHeaderChainWithDiff(genesis, []int{1, 2, 3, 4}, 10)
  521. blocks := makeBlockChainWithDiff(genesis, []int{1, 2, 3, 4}, 10)
  522. if full {
  523. if _, err := bc.InsertChain(blocks); err != nil {
  524. t.Fatalf("failed to import blocks: %v", err)
  525. }
  526. if bc.CurrentBlock().Hash() != blocks[3].Hash() {
  527. t.Errorf("last block hash mismatch: have: %x, want %x", bc.CurrentBlock().Hash(), blocks[3].Header().Hash())
  528. }
  529. BadHashes[blocks[3].Header().Hash()] = true
  530. defer func() { delete(BadHashes, blocks[3].Header().Hash()) }()
  531. } else {
  532. if _, err := bc.InsertHeaderChain(headers, 1); err != nil {
  533. t.Fatalf("failed to import headers: %v", err)
  534. }
  535. if bc.CurrentHeader().Hash() != headers[3].Hash() {
  536. t.Errorf("last header hash mismatch: have: %x, want %x", bc.CurrentHeader().Hash(), headers[3].Hash())
  537. }
  538. BadHashes[headers[3].Hash()] = true
  539. defer func() { delete(BadHashes, headers[3].Hash()) }()
  540. }
  541. // Create a new chain manager and check it rolled back the state
  542. ncm, err := NewBlockChain(db, FakePow{}, new(event.TypeMux))
  543. if err != nil {
  544. t.Fatalf("failed to create new chain manager: %v", err)
  545. }
  546. if full {
  547. if ncm.CurrentBlock().Hash() != blocks[2].Header().Hash() {
  548. t.Errorf("last block hash mismatch: have: %x, want %x", ncm.CurrentBlock().Hash(), blocks[2].Header().Hash())
  549. }
  550. if blocks[2].Header().GasLimit.Cmp(ncm.GasLimit()) != 0 {
  551. t.Errorf("last block gasLimit mismatch: have: %x, want %x", ncm.GasLimit(), blocks[2].Header().GasLimit)
  552. }
  553. } else {
  554. if ncm.CurrentHeader().Hash() != headers[2].Hash() {
  555. t.Errorf("last header hash mismatch: have: %x, want %x", ncm.CurrentHeader().Hash(), headers[2].Hash())
  556. }
  557. }
  558. }
  559. // Tests chain insertions in the face of one entity containing an invalid nonce.
  560. func TestHeadersInsertNonceError(t *testing.T) { testInsertNonceError(t, false) }
  561. func TestBlocksInsertNonceError(t *testing.T) { testInsertNonceError(t, true) }
  562. func testInsertNonceError(t *testing.T, full bool) {
  563. for i := 1; i < 25 && !t.Failed(); i++ {
  564. // Create a pristine chain and database
  565. db, blockchain, err := newCanonical(0, full)
  566. if err != nil {
  567. t.Fatalf("failed to create pristine chain: %v", err)
  568. }
  569. // Create and insert a chain with a failing nonce
  570. var (
  571. failAt int
  572. failRes int
  573. failNum uint64
  574. failHash common.Hash
  575. )
  576. if full {
  577. blocks := makeBlockChain(blockchain.CurrentBlock(), i, db, 0)
  578. failAt = rand.Int() % len(blocks)
  579. failNum = blocks[failAt].NumberU64()
  580. failHash = blocks[failAt].Hash()
  581. blockchain.pow = failPow{failNum}
  582. failRes, err = blockchain.InsertChain(blocks)
  583. } else {
  584. headers := makeHeaderChain(blockchain.CurrentHeader(), i, db, 0)
  585. failAt = rand.Int() % len(headers)
  586. failNum = headers[failAt].Number.Uint64()
  587. failHash = headers[failAt].Hash()
  588. blockchain.pow = failPow{failNum}
  589. blockchain.validator = NewBlockValidator(blockchain, failPow{failNum})
  590. failRes, err = blockchain.InsertHeaderChain(headers, 1)
  591. }
  592. // Check that the returned error indicates the nonce failure.
  593. if failRes != failAt {
  594. t.Errorf("test %d: failure index mismatch: have %d, want %d", i, failRes, failAt)
  595. }
  596. if !IsBlockNonceErr(err) {
  597. t.Fatalf("test %d: error mismatch: have %v, want nonce error %T", i, err, err)
  598. }
  599. nerr := err.(*BlockNonceErr)
  600. if nerr.Number.Uint64() != failNum {
  601. t.Errorf("test %d: number mismatch: have %v, want %v", i, nerr.Number, failNum)
  602. }
  603. if nerr.Hash != failHash {
  604. t.Errorf("test %d: hash mismatch: have %x, want %x", i, nerr.Hash[:4], failHash[:4])
  605. }
  606. // Check that all no blocks after the failing block have been inserted.
  607. for j := 0; j < i-failAt; j++ {
  608. if full {
  609. if block := blockchain.GetBlockByNumber(failNum + uint64(j)); block != nil {
  610. t.Errorf("test %d: invalid block in chain: %v", i, block)
  611. }
  612. } else {
  613. if header := blockchain.GetHeaderByNumber(failNum + uint64(j)); header != nil {
  614. t.Errorf("test %d: invalid header in chain: %v", i, header)
  615. }
  616. }
  617. }
  618. }
  619. }
  620. // Tests that fast importing a block chain produces the same chain data as the
  621. // classical full block processing.
  622. func TestFastVsFullChains(t *testing.T) {
  623. // Configure and generate a sample block chain
  624. var (
  625. gendb, _ = ethdb.NewMemDatabase()
  626. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  627. address = crypto.PubkeyToAddress(key.PublicKey)
  628. funds = big.NewInt(1000000000)
  629. genesis = GenesisBlockForTesting(gendb, address, funds)
  630. )
  631. blocks, receipts := GenerateChain(genesis, gendb, 1024, func(i int, block *BlockGen) {
  632. block.SetCoinbase(common.Address{0x00})
  633. // If the block number is multiple of 3, send a few bonus transactions to the miner
  634. if i%3 == 2 {
  635. for j := 0; j < i%4+1; j++ {
  636. tx, err := types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key)
  637. if err != nil {
  638. panic(err)
  639. }
  640. block.AddTx(tx)
  641. }
  642. }
  643. // If the block number is a multiple of 5, add a few bonus uncles to the block
  644. if i%5 == 5 {
  645. block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))})
  646. }
  647. })
  648. // Import the chain as an archive node for the comparison baseline
  649. archiveDb, _ := ethdb.NewMemDatabase()
  650. WriteGenesisBlockForTesting(archiveDb, GenesisAccount{address, funds})
  651. archive, _ := NewBlockChain(archiveDb, FakePow{}, new(event.TypeMux))
  652. if n, err := archive.InsertChain(blocks); err != nil {
  653. t.Fatalf("failed to process block %d: %v", n, err)
  654. }
  655. // Fast import the chain as a non-archive node to test
  656. fastDb, _ := ethdb.NewMemDatabase()
  657. WriteGenesisBlockForTesting(fastDb, GenesisAccount{address, funds})
  658. fast, _ := NewBlockChain(fastDb, FakePow{}, new(event.TypeMux))
  659. headers := make([]*types.Header, len(blocks))
  660. for i, block := range blocks {
  661. headers[i] = block.Header()
  662. }
  663. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  664. t.Fatalf("failed to insert header %d: %v", n, err)
  665. }
  666. if n, err := fast.InsertReceiptChain(blocks, receipts); err != nil {
  667. t.Fatalf("failed to insert receipt %d: %v", n, err)
  668. }
  669. // Iterate over all chain data components, and cross reference
  670. for i := 0; i < len(blocks); i++ {
  671. num, hash := blocks[i].NumberU64(), blocks[i].Hash()
  672. if ftd, atd := fast.GetTd(hash), archive.GetTd(hash); ftd.Cmp(atd) != 0 {
  673. t.Errorf("block #%d [%x]: td mismatch: have %v, want %v", num, hash, ftd, atd)
  674. }
  675. if fheader, aheader := fast.GetHeader(hash), archive.GetHeader(hash); fheader.Hash() != aheader.Hash() {
  676. t.Errorf("block #%d [%x]: header mismatch: have %v, want %v", num, hash, fheader, aheader)
  677. }
  678. if fblock, ablock := fast.GetBlock(hash), archive.GetBlock(hash); fblock.Hash() != ablock.Hash() {
  679. t.Errorf("block #%d [%x]: block mismatch: have %v, want %v", num, hash, fblock, ablock)
  680. } else if types.DeriveSha(fblock.Transactions()) != types.DeriveSha(ablock.Transactions()) {
  681. t.Errorf("block #%d [%x]: transactions mismatch: have %v, want %v", num, hash, fblock.Transactions(), ablock.Transactions())
  682. } else if types.CalcUncleHash(fblock.Uncles()) != types.CalcUncleHash(ablock.Uncles()) {
  683. t.Errorf("block #%d [%x]: uncles mismatch: have %v, want %v", num, hash, fblock.Uncles(), ablock.Uncles())
  684. }
  685. if freceipts, areceipts := GetBlockReceipts(fastDb, hash), GetBlockReceipts(archiveDb, hash); types.DeriveSha(freceipts) != types.DeriveSha(areceipts) {
  686. t.Errorf("block #%d [%x]: receipts mismatch: have %v, want %v", num, hash, freceipts, areceipts)
  687. }
  688. }
  689. // Check that the canonical chains are the same between the databases
  690. for i := 0; i < len(blocks)+1; i++ {
  691. if fhash, ahash := GetCanonicalHash(fastDb, uint64(i)), GetCanonicalHash(archiveDb, uint64(i)); fhash != ahash {
  692. t.Errorf("block #%d: canonical hash mismatch: have %v, want %v", i, fhash, ahash)
  693. }
  694. }
  695. }
  696. // Tests that various import methods move the chain head pointers to the correct
  697. // positions.
  698. func TestLightVsFastVsFullChainHeads(t *testing.T) {
  699. // Configure and generate a sample block chain
  700. var (
  701. gendb, _ = ethdb.NewMemDatabase()
  702. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  703. address = crypto.PubkeyToAddress(key.PublicKey)
  704. funds = big.NewInt(1000000000)
  705. genesis = GenesisBlockForTesting(gendb, address, funds)
  706. )
  707. height := uint64(1024)
  708. blocks, receipts := GenerateChain(genesis, gendb, int(height), nil)
  709. // Configure a subchain to roll back
  710. remove := []common.Hash{}
  711. for _, block := range blocks[height/2:] {
  712. remove = append(remove, block.Hash())
  713. }
  714. // Create a small assertion method to check the three heads
  715. assert := func(t *testing.T, kind string, chain *BlockChain, header uint64, fast uint64, block uint64) {
  716. if num := chain.CurrentBlock().NumberU64(); num != block {
  717. t.Errorf("%s head block mismatch: have #%v, want #%v", kind, num, block)
  718. }
  719. if num := chain.CurrentFastBlock().NumberU64(); num != fast {
  720. t.Errorf("%s head fast-block mismatch: have #%v, want #%v", kind, num, fast)
  721. }
  722. if num := chain.CurrentHeader().Number.Uint64(); num != header {
  723. t.Errorf("%s head header mismatch: have #%v, want #%v", kind, num, header)
  724. }
  725. }
  726. // Import the chain as an archive node and ensure all pointers are updated
  727. archiveDb, _ := ethdb.NewMemDatabase()
  728. WriteGenesisBlockForTesting(archiveDb, GenesisAccount{address, funds})
  729. archive, _ := NewBlockChain(archiveDb, FakePow{}, new(event.TypeMux))
  730. if n, err := archive.InsertChain(blocks); err != nil {
  731. t.Fatalf("failed to process block %d: %v", n, err)
  732. }
  733. assert(t, "archive", archive, height, height, height)
  734. archive.Rollback(remove)
  735. assert(t, "archive", archive, height/2, height/2, height/2)
  736. // Import the chain as a non-archive node and ensure all pointers are updated
  737. fastDb, _ := ethdb.NewMemDatabase()
  738. WriteGenesisBlockForTesting(fastDb, GenesisAccount{address, funds})
  739. fast, _ := NewBlockChain(fastDb, FakePow{}, new(event.TypeMux))
  740. headers := make([]*types.Header, len(blocks))
  741. for i, block := range blocks {
  742. headers[i] = block.Header()
  743. }
  744. if n, err := fast.InsertHeaderChain(headers, 1); err != nil {
  745. t.Fatalf("failed to insert header %d: %v", n, err)
  746. }
  747. if n, err := fast.InsertReceiptChain(blocks, receipts); err != nil {
  748. t.Fatalf("failed to insert receipt %d: %v", n, err)
  749. }
  750. assert(t, "fast", fast, height, height, 0)
  751. fast.Rollback(remove)
  752. assert(t, "fast", fast, height/2, height/2, 0)
  753. // Import the chain as a light node and ensure all pointers are updated
  754. lightDb, _ := ethdb.NewMemDatabase()
  755. WriteGenesisBlockForTesting(lightDb, GenesisAccount{address, funds})
  756. light, _ := NewBlockChain(lightDb, FakePow{}, new(event.TypeMux))
  757. if n, err := light.InsertHeaderChain(headers, 1); err != nil {
  758. t.Fatalf("failed to insert header %d: %v", n, err)
  759. }
  760. assert(t, "light", light, height, 0, 0)
  761. light.Rollback(remove)
  762. assert(t, "light", light, height/2, 0, 0)
  763. }
  764. // Tests that chain reorganizations handle transaction removals and reinsertions.
  765. func TestChainTxReorgs(t *testing.T) {
  766. params.MinGasLimit = big.NewInt(125000) // Minimum the gas limit may ever be.
  767. params.GenesisGasLimit = big.NewInt(3141592) // Gas limit of the Genesis block.
  768. var (
  769. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  770. key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  771. key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  772. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  773. addr2 = crypto.PubkeyToAddress(key2.PublicKey)
  774. addr3 = crypto.PubkeyToAddress(key3.PublicKey)
  775. db, _ = ethdb.NewMemDatabase()
  776. )
  777. genesis := WriteGenesisBlockForTesting(db,
  778. GenesisAccount{addr1, big.NewInt(1000000)},
  779. GenesisAccount{addr2, big.NewInt(1000000)},
  780. GenesisAccount{addr3, big.NewInt(1000000)},
  781. )
  782. // Create two transactions shared between the chains:
  783. // - postponed: transaction included at a later block in the forked chain
  784. // - swapped: transaction included at the same block number in the forked chain
  785. postponed, _ := types.NewTransaction(0, addr1, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
  786. swapped, _ := types.NewTransaction(1, addr1, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key1)
  787. // Create two transactions that will be dropped by the forked chain:
  788. // - pastDrop: transaction dropped retroactively from a past block
  789. // - freshDrop: transaction dropped exactly at the block where the reorg is detected
  790. var pastDrop, freshDrop *types.Transaction
  791. // Create three transactions that will be added in the forked chain:
  792. // - pastAdd: transaction added before the reorganiztion is detected
  793. // - freshAdd: transaction added at the exact block the reorg is detected
  794. // - futureAdd: transaction added after the reorg has already finished
  795. var pastAdd, freshAdd, futureAdd *types.Transaction
  796. chain, _ := GenerateChain(genesis, db, 3, func(i int, gen *BlockGen) {
  797. switch i {
  798. case 0:
  799. pastDrop, _ = types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
  800. gen.AddTx(pastDrop) // This transaction will be dropped in the fork from below the split point
  801. gen.AddTx(postponed) // This transaction will be postponed till block #3 in the fork
  802. case 2:
  803. freshDrop, _ = types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key2)
  804. gen.AddTx(freshDrop) // This transaction will be dropped in the fork from exactly at the split point
  805. gen.AddTx(swapped) // This transaction will be swapped out at the exact height
  806. gen.OffsetTime(9) // Lower the block difficulty to simulate a weaker chain
  807. }
  808. })
  809. // Import the chain. This runs all block validation rules.
  810. evmux := &event.TypeMux{}
  811. blockchain, _ := NewBlockChain(db, FakePow{}, evmux)
  812. if i, err := blockchain.InsertChain(chain); err != nil {
  813. t.Fatalf("failed to insert original chain[%d]: %v", i, err)
  814. }
  815. // overwrite the old chain
  816. chain, _ = GenerateChain(genesis, db, 5, func(i int, gen *BlockGen) {
  817. switch i {
  818. case 0:
  819. pastAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
  820. gen.AddTx(pastAdd) // This transaction needs to be injected during reorg
  821. case 2:
  822. gen.AddTx(postponed) // This transaction was postponed from block #1 in the original chain
  823. gen.AddTx(swapped) // This transaction was swapped from the exact current spot in the original chain
  824. freshAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
  825. gen.AddTx(freshAdd) // This transaction will be added exactly at reorg time
  826. case 3:
  827. futureAdd, _ = types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(key3)
  828. gen.AddTx(futureAdd) // This transaction will be added after a full reorg
  829. }
  830. })
  831. if _, err := blockchain.InsertChain(chain); err != nil {
  832. t.Fatalf("failed to insert forked chain: %v", err)
  833. }
  834. // removed tx
  835. for i, tx := range (types.Transactions{pastDrop, freshDrop}) {
  836. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn != nil {
  837. t.Errorf("drop %d: tx %v found while shouldn't have been", i, txn)
  838. }
  839. if GetReceipt(db, tx.Hash()) != nil {
  840. t.Errorf("drop %d: receipt found while shouldn't have been", i)
  841. }
  842. }
  843. // added tx
  844. for i, tx := range (types.Transactions{pastAdd, freshAdd, futureAdd}) {
  845. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn == nil {
  846. t.Errorf("add %d: expected tx to be found", i)
  847. }
  848. if GetReceipt(db, tx.Hash()) == nil {
  849. t.Errorf("add %d: expected receipt to be found", i)
  850. }
  851. }
  852. // shared tx
  853. for i, tx := range (types.Transactions{postponed, swapped}) {
  854. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn == nil {
  855. t.Errorf("share %d: expected tx to be found", i)
  856. }
  857. if GetReceipt(db, tx.Hash()) == nil {
  858. t.Errorf("share %d: expected receipt to be found", i)
  859. }
  860. }
  861. }
  862. func TestLogReorgs(t *testing.T) {
  863. params.MinGasLimit = big.NewInt(125000) // Minimum the gas limit may ever be.
  864. params.GenesisGasLimit = big.NewInt(3141592) // Gas limit of the Genesis block.
  865. var (
  866. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  867. addr1 = crypto.PubkeyToAddress(key1.PublicKey)
  868. db, _ = ethdb.NewMemDatabase()
  869. // this code generates a log
  870. code = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
  871. )
  872. genesis := WriteGenesisBlockForTesting(db,
  873. GenesisAccount{addr1, big.NewInt(10000000000000)},
  874. )
  875. evmux := &event.TypeMux{}
  876. blockchain, _ := NewBlockChain(db, FakePow{}, evmux)
  877. subs := evmux.Subscribe(RemovedLogsEvent{})
  878. chain, _ := GenerateChain(genesis, db, 2, func(i int, gen *BlockGen) {
  879. if i == 1 {
  880. tx, err := types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), big.NewInt(1000000), new(big.Int), code).SignECDSA(key1)
  881. if err != nil {
  882. t.Fatalf("failed to create tx: %v", err)
  883. }
  884. gen.AddTx(tx)
  885. }
  886. })
  887. if _, err := blockchain.InsertChain(chain); err != nil {
  888. t.Fatalf("failed to insert chain: %v", err)
  889. }
  890. chain, _ = GenerateChain(genesis, db, 3, func(i int, gen *BlockGen) {})
  891. if _, err := blockchain.InsertChain(chain); err != nil {
  892. t.Fatalf("failed to insert forked chain: %v", err)
  893. }
  894. ev := <-subs.Chan()
  895. if len(ev.Data.(RemovedLogsEvent).Logs) == 0 {
  896. t.Error("expected logs")
  897. }
  898. }