blockchain_test.go 34 KB

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