chain_manager_test.go 13 KB

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