chain_manager_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. 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/ethdb"
  31. "github.com/ethereum/go-ethereum/event"
  32. "github.com/ethereum/go-ethereum/pow"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. "github.com/hashicorp/golang-lru"
  35. )
  36. func init() {
  37. runtime.GOMAXPROCS(runtime.NumCPU())
  38. }
  39. func thePow() pow.PoW {
  40. pow, _ := ethash.NewForTesting()
  41. return pow
  42. }
  43. func theChainManager(db common.Database, t *testing.T) *ChainManager {
  44. var eventMux event.TypeMux
  45. genesis := GenesisBlock(0, db)
  46. chainMan, err := NewChainManager(genesis, db, db, db, thePow(), &eventMux)
  47. if err != nil {
  48. t.Error("failed creating chainmanager:", err)
  49. t.FailNow()
  50. return nil
  51. }
  52. blockMan := NewBlockProcessor(db, db, nil, chainMan, &eventMux)
  53. chainMan.SetProcessor(blockMan)
  54. return chainMan
  55. }
  56. // Test fork of length N starting from block i
  57. func testFork(t *testing.T, bman *BlockProcessor, i, N int, f func(td1, td2 *big.Int)) {
  58. // switch databases to process the new chain
  59. db, err := ethdb.NewMemDatabase()
  60. if err != nil {
  61. t.Fatal("Failed to create db:", err)
  62. }
  63. // copy old chain up to i into new db with deterministic canonical
  64. bman2, err := newCanonical(i, db)
  65. if err != nil {
  66. t.Fatal("could not make new canonical in testFork", err)
  67. }
  68. // asert the bmans have the same block at i
  69. bi1 := bman.bc.GetBlockByNumber(uint64(i)).Hash()
  70. bi2 := bman2.bc.GetBlockByNumber(uint64(i)).Hash()
  71. if bi1 != bi2 {
  72. t.Fatal("chains do not have the same hash at height", i)
  73. }
  74. bman2.bc.SetProcessor(bman2)
  75. // extend the fork
  76. parent := bman2.bc.CurrentBlock()
  77. chainB := makeChain(parent, N, db, forkSeed)
  78. _, err = bman2.bc.InsertChain(chainB)
  79. if err != nil {
  80. t.Fatal("Insert chain error for fork:", err)
  81. }
  82. tdpre := bman.bc.Td()
  83. // Test the fork's blocks on the original chain
  84. td, err := testChain(chainB, bman)
  85. if err != nil {
  86. t.Fatal("expected chainB not to give errors:", err)
  87. }
  88. // Compare difficulties
  89. f(tdpre, td)
  90. // Loop over parents making sure reconstruction is done properly
  91. }
  92. func printChain(bc *ChainManager) {
  93. for i := bc.CurrentBlock().Number().Uint64(); i > 0; i-- {
  94. b := bc.GetBlockByNumber(uint64(i))
  95. fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty())
  96. }
  97. }
  98. // process blocks against a chain
  99. func testChain(chainB types.Blocks, bman *BlockProcessor) (*big.Int, error) {
  100. td := new(big.Int)
  101. for _, block := range chainB {
  102. _, _, err := bman.bc.processor.Process(block)
  103. if err != nil {
  104. if IsKnownBlockErr(err) {
  105. continue
  106. }
  107. return nil, err
  108. }
  109. parent := bman.bc.GetBlock(block.ParentHash())
  110. block.Td = CalcTD(block, parent)
  111. td = block.Td
  112. bman.bc.mu.Lock()
  113. {
  114. bman.bc.write(block)
  115. }
  116. bman.bc.mu.Unlock()
  117. }
  118. return td, nil
  119. }
  120. func loadChain(fn string, t *testing.T) (types.Blocks, error) {
  121. fh, err := os.OpenFile(filepath.Join("..", "_data", fn), os.O_RDONLY, os.ModePerm)
  122. if err != nil {
  123. return nil, err
  124. }
  125. defer fh.Close()
  126. var chain types.Blocks
  127. if err := rlp.Decode(fh, &chain); err != nil {
  128. return nil, err
  129. }
  130. return chain, nil
  131. }
  132. func insertChain(done chan bool, chainMan *ChainManager, chain types.Blocks, t *testing.T) {
  133. _, err := chainMan.InsertChain(chain)
  134. if err != nil {
  135. fmt.Println(err)
  136. t.FailNow()
  137. }
  138. done <- true
  139. }
  140. func TestExtendCanonical(t *testing.T) {
  141. CanonicalLength := 5
  142. db, err := ethdb.NewMemDatabase()
  143. if err != nil {
  144. t.Fatal("Failed to create db:", err)
  145. }
  146. // make first chain starting from genesis
  147. bman, err := newCanonical(CanonicalLength, db)
  148. if err != nil {
  149. t.Fatal("Could not make new canonical chain:", err)
  150. }
  151. f := func(td1, td2 *big.Int) {
  152. if td2.Cmp(td1) <= 0 {
  153. t.Error("expected chainB to have higher difficulty. Got", td2, "expected more than", td1)
  154. }
  155. }
  156. // Start fork from current height (CanonicalLength)
  157. testFork(t, bman, CanonicalLength, 1, f)
  158. testFork(t, bman, CanonicalLength, 2, f)
  159. testFork(t, bman, CanonicalLength, 5, f)
  160. testFork(t, bman, CanonicalLength, 10, f)
  161. }
  162. func TestShorterFork(t *testing.T) {
  163. db, err := ethdb.NewMemDatabase()
  164. if err != nil {
  165. t.Fatal("Failed to create db:", err)
  166. }
  167. // make first chain starting from genesis
  168. bman, err := newCanonical(10, db)
  169. if err != nil {
  170. t.Fatal("Could not make new canonical chain:", err)
  171. }
  172. f := func(td1, td2 *big.Int) {
  173. if td2.Cmp(td1) >= 0 {
  174. t.Error("expected chainB to have lower difficulty. Got", td2, "expected less than", td1)
  175. }
  176. }
  177. // Sum of numbers must be less than 10
  178. // for this to be a shorter fork
  179. testFork(t, bman, 0, 3, f)
  180. testFork(t, bman, 0, 7, f)
  181. testFork(t, bman, 1, 1, f)
  182. testFork(t, bman, 1, 7, f)
  183. testFork(t, bman, 5, 3, f)
  184. testFork(t, bman, 5, 4, f)
  185. }
  186. func TestLongerFork(t *testing.T) {
  187. db, err := ethdb.NewMemDatabase()
  188. if err != nil {
  189. t.Fatal("Failed to create db:", err)
  190. }
  191. // make first chain starting from genesis
  192. bman, err := newCanonical(10, db)
  193. if err != nil {
  194. t.Fatal("Could not make new canonical chain:", err)
  195. }
  196. f := func(td1, td2 *big.Int) {
  197. if td2.Cmp(td1) <= 0 {
  198. t.Error("expected chainB to have higher difficulty. Got", td2, "expected more than", td1)
  199. }
  200. }
  201. // Sum of numbers must be greater than 10
  202. // for this to be a longer fork
  203. testFork(t, bman, 0, 11, f)
  204. testFork(t, bman, 0, 15, f)
  205. testFork(t, bman, 1, 10, f)
  206. testFork(t, bman, 1, 12, f)
  207. testFork(t, bman, 5, 6, f)
  208. testFork(t, bman, 5, 8, f)
  209. }
  210. func TestEqualFork(t *testing.T) {
  211. db, err := ethdb.NewMemDatabase()
  212. if err != nil {
  213. t.Fatal("Failed to create db:", err)
  214. }
  215. bman, err := newCanonical(10, db)
  216. if err != nil {
  217. t.Fatal("Could not make new canonical chain:", err)
  218. }
  219. f := func(td1, td2 *big.Int) {
  220. if td2.Cmp(td1) != 0 {
  221. t.Error("expected chainB to have equal difficulty. Got", td2, "expected ", td1)
  222. }
  223. }
  224. // Sum of numbers must be equal to 10
  225. // for this to be an equal fork
  226. testFork(t, bman, 0, 10, f)
  227. testFork(t, bman, 1, 9, f)
  228. testFork(t, bman, 2, 8, f)
  229. testFork(t, bman, 5, 5, f)
  230. testFork(t, bman, 6, 4, f)
  231. testFork(t, bman, 9, 1, f)
  232. }
  233. func TestBrokenChain(t *testing.T) {
  234. db, err := ethdb.NewMemDatabase()
  235. if err != nil {
  236. t.Fatal("Failed to create db:", err)
  237. }
  238. bman, err := newCanonical(10, db)
  239. if err != nil {
  240. t.Fatal("Could not make new canonical chain:", err)
  241. }
  242. db2, err := ethdb.NewMemDatabase()
  243. if err != nil {
  244. t.Fatal("Failed to create db:", err)
  245. }
  246. bman2, err := newCanonical(10, db2)
  247. if err != nil {
  248. t.Fatal("Could not make new canonical chain:", err)
  249. }
  250. bman2.bc.SetProcessor(bman2)
  251. parent := bman2.bc.CurrentBlock()
  252. chainB := makeChain(parent, 5, db2, forkSeed)
  253. chainB = chainB[1:]
  254. _, err = testChain(chainB, bman)
  255. if err == nil {
  256. t.Error("expected broken chain to return error")
  257. }
  258. }
  259. func TestChainInsertions(t *testing.T) {
  260. t.Skip("Skipped: outdated test files")
  261. db, _ := ethdb.NewMemDatabase()
  262. chain1, err := loadChain("valid1", t)
  263. if err != nil {
  264. fmt.Println(err)
  265. t.FailNow()
  266. }
  267. chain2, err := loadChain("valid2", t)
  268. if err != nil {
  269. fmt.Println(err)
  270. t.FailNow()
  271. }
  272. chainMan := theChainManager(db, t)
  273. const max = 2
  274. done := make(chan bool, max)
  275. go insertChain(done, chainMan, chain1, t)
  276. go insertChain(done, chainMan, chain2, t)
  277. for i := 0; i < max; i++ {
  278. <-done
  279. }
  280. if chain2[len(chain2)-1].Hash() != chainMan.CurrentBlock().Hash() {
  281. t.Error("chain2 is canonical and shouldn't be")
  282. }
  283. if chain1[len(chain1)-1].Hash() != chainMan.CurrentBlock().Hash() {
  284. t.Error("chain1 isn't canonical and should be")
  285. }
  286. }
  287. func TestChainMultipleInsertions(t *testing.T) {
  288. t.Skip("Skipped: outdated test files")
  289. db, _ := ethdb.NewMemDatabase()
  290. const max = 4
  291. chains := make([]types.Blocks, max)
  292. var longest int
  293. for i := 0; i < max; i++ {
  294. var err error
  295. name := "valid" + strconv.Itoa(i+1)
  296. chains[i], err = loadChain(name, t)
  297. if len(chains[i]) >= len(chains[longest]) {
  298. longest = i
  299. }
  300. fmt.Println("loaded", name, "with a length of", len(chains[i]))
  301. if err != nil {
  302. fmt.Println(err)
  303. t.FailNow()
  304. }
  305. }
  306. chainMan := theChainManager(db, t)
  307. done := make(chan bool, max)
  308. for i, chain := range chains {
  309. // XXX the go routine would otherwise reference the same (chain[3]) variable and fail
  310. i := i
  311. chain := chain
  312. go func() {
  313. insertChain(done, chainMan, chain, t)
  314. fmt.Println(i, "done")
  315. }()
  316. }
  317. for i := 0; i < max; i++ {
  318. <-done
  319. }
  320. if chains[longest][len(chains[longest])-1].Hash() != chainMan.CurrentBlock().Hash() {
  321. t.Error("Invalid canonical chain")
  322. }
  323. }
  324. func TestGetBlocksFromHash(t *testing.T) {
  325. t.Skip("Skipped: outdated test files")
  326. db, _ := ethdb.NewMemDatabase()
  327. chainMan := theChainManager(db, t)
  328. chain, err := loadChain("valid1", t)
  329. if err != nil {
  330. fmt.Println(err)
  331. t.FailNow()
  332. }
  333. for _, block := range chain {
  334. chainMan.write(block)
  335. }
  336. blocks := chainMan.GetBlocksFromHash(chain[len(chain)-1].Hash(), 4)
  337. fmt.Println(blocks)
  338. }
  339. type bproc struct{}
  340. func (bproc) Process(*types.Block) (state.Logs, types.Receipts, error) { return nil, nil, nil }
  341. func makeChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Block {
  342. var chain []*types.Block
  343. for i, difficulty := range d {
  344. header := &types.Header{
  345. Coinbase: common.Address{seed},
  346. Number: big.NewInt(int64(i + 1)),
  347. Difficulty: big.NewInt(int64(difficulty)),
  348. }
  349. if i == 0 {
  350. header.ParentHash = genesis.Hash()
  351. } else {
  352. header.ParentHash = chain[i-1].Hash()
  353. }
  354. block := types.NewBlockWithHeader(header)
  355. chain = append(chain, block)
  356. }
  357. return chain
  358. }
  359. func chm(genesis *types.Block, db common.Database) *ChainManager {
  360. var eventMux event.TypeMux
  361. bc := &ChainManager{extraDb: db, blockDb: db, stateDb: db, genesisBlock: genesis, eventMux: &eventMux, pow: FakePow{}}
  362. bc.cache, _ = lru.New(100)
  363. bc.futureBlocks, _ = lru.New(100)
  364. bc.processor = bproc{}
  365. bc.ResetWithGenesisBlock(genesis)
  366. bc.txState = state.ManageState(bc.State())
  367. return bc
  368. }
  369. func TestReorgLongest(t *testing.T) {
  370. db, _ := ethdb.NewMemDatabase()
  371. genesis := GenesisBlock(0, db)
  372. bc := chm(genesis, db)
  373. chain1 := makeChainWithDiff(genesis, []int{1, 2, 4}, 10)
  374. chain2 := makeChainWithDiff(genesis, []int{1, 2, 3, 4}, 11)
  375. bc.InsertChain(chain1)
  376. bc.InsertChain(chain2)
  377. prev := bc.CurrentBlock()
  378. for block := bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 1); block.NumberU64() != 0; prev, block = block, bc.GetBlockByNumber(block.NumberU64()-1) {
  379. if prev.ParentHash() != block.Hash() {
  380. t.Errorf("parent hash mismatch %x - %x", prev.ParentHash(), block.Hash())
  381. }
  382. }
  383. }
  384. func TestReorgShortest(t *testing.T) {
  385. db, _ := ethdb.NewMemDatabase()
  386. genesis := GenesisBlock(0, db)
  387. bc := chm(genesis, db)
  388. chain1 := makeChainWithDiff(genesis, []int{1, 2, 3, 4}, 10)
  389. chain2 := makeChainWithDiff(genesis, []int{1, 10}, 11)
  390. bc.InsertChain(chain1)
  391. bc.InsertChain(chain2)
  392. prev := bc.CurrentBlock()
  393. for block := bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 1); block.NumberU64() != 0; prev, block = block, bc.GetBlockByNumber(block.NumberU64()-1) {
  394. if prev.ParentHash() != block.Hash() {
  395. t.Errorf("parent hash mismatch %x - %x", prev.ParentHash(), block.Hash())
  396. }
  397. }
  398. }
  399. func TestInsertNonceError(t *testing.T) {
  400. for i := 1; i < 25 && !t.Failed(); i++ {
  401. db, _ := ethdb.NewMemDatabase()
  402. genesis := GenesisBlock(0, db)
  403. bc := chm(genesis, db)
  404. bc.processor = NewBlockProcessor(db, db, bc.pow, bc, bc.eventMux)
  405. blocks := makeChain(bc.currentBlock, i, db, 0)
  406. fail := rand.Int() % len(blocks)
  407. failblock := blocks[fail]
  408. bc.pow = failpow{failblock.NumberU64()}
  409. n, err := bc.InsertChain(blocks)
  410. // Check that the returned error indicates the nonce failure.
  411. if n != fail {
  412. t.Errorf("(i=%d) wrong failed block index: got %d, want %d", i, n, fail)
  413. }
  414. if !IsBlockNonceErr(err) {
  415. t.Fatalf("(i=%d) got %q, want a nonce error", i, err)
  416. }
  417. nerr := err.(*BlockNonceErr)
  418. if nerr.Number.Cmp(failblock.Number()) != 0 {
  419. t.Errorf("(i=%d) wrong block number in error, got %v, want %v", i, nerr.Number, failblock.Number())
  420. }
  421. if nerr.Hash != failblock.Hash() {
  422. t.Errorf("(i=%d) wrong block hash in error, got %v, want %v", i, nerr.Hash, failblock.Hash())
  423. }
  424. // Check that all no blocks after the failing block have been inserted.
  425. for _, block := range blocks[fail:] {
  426. if bc.HasBlock(block.Hash()) {
  427. t.Errorf("(i=%d) invalid block %d present in chain", i, block.NumberU64())
  428. }
  429. }
  430. }
  431. }
  432. func TestGenesisMismatch(t *testing.T) {
  433. db, _ := ethdb.NewMemDatabase()
  434. var mux event.TypeMux
  435. genesis := GenesisBlock(0, db)
  436. _, err := NewChainManager(genesis, db, db, db, thePow(), &mux)
  437. if err != nil {
  438. t.Error(err)
  439. }
  440. genesis = GenesisBlock(1, db)
  441. _, err = NewChainManager(genesis, db, db, db, thePow(), &mux)
  442. if err == nil {
  443. t.Error("expected genesis mismatch error")
  444. }
  445. }
  446. // failpow returns false from Verify for a certain block number.
  447. type failpow struct{ num uint64 }
  448. func (pow failpow) Search(pow.Block, <-chan struct{}) (nonce uint64, mixHash []byte) {
  449. return 0, nil
  450. }
  451. func (pow failpow) Verify(b pow.Block) bool {
  452. return b.NumberU64() != pow.num
  453. }
  454. func (pow failpow) GetHashrate() int64 {
  455. return 0
  456. }
  457. func (pow failpow) Turbo(bool) {
  458. }