chain_manager_test.go 13 KB

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