chain_manager_test.go 13 KB

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