chain_manager_test.go 11 KB

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