lightchain_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library 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. // The go-ethereum library 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package light
  17. import (
  18. "context"
  19. "math/big"
  20. "testing"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/consensus/ethash"
  23. "github.com/ethereum/go-ethereum/core"
  24. "github.com/ethereum/go-ethereum/core/rawdb"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/ethdb"
  27. "github.com/ethereum/go-ethereum/params"
  28. )
  29. // So we can deterministically seed different blockchains
  30. var (
  31. canonicalSeed = 1
  32. forkSeed = 2
  33. )
  34. // makeHeaderChain creates a deterministic chain of headers rooted at parent.
  35. func makeHeaderChain(parent *types.Header, n int, db ethdb.Database, seed int) []*types.Header {
  36. blocks, _ := core.GenerateChain(params.TestChainConfig, types.NewBlockWithHeader(parent), ethash.NewFaker(), db, n, func(i int, b *core.BlockGen) {
  37. b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
  38. })
  39. headers := make([]*types.Header, len(blocks))
  40. for i, block := range blocks {
  41. headers[i] = block.Header()
  42. }
  43. return headers
  44. }
  45. // newCanonical creates a chain database, and injects a deterministic canonical
  46. // chain. Depending on the full flag, if creates either a full block chain or a
  47. // header only chain.
  48. func newCanonical(n int) (ethdb.Database, *LightChain, error) {
  49. db := ethdb.NewMemDatabase()
  50. gspec := core.Genesis{Config: params.TestChainConfig}
  51. genesis := gspec.MustCommit(db)
  52. blockchain, _ := NewLightChain(&dummyOdr{db: db}, gspec.Config, ethash.NewFaker())
  53. // Create and inject the requested chain
  54. if n == 0 {
  55. return db, blockchain, nil
  56. }
  57. // Header-only chain requested
  58. headers := makeHeaderChain(genesis.Header(), n, db, canonicalSeed)
  59. _, err := blockchain.InsertHeaderChain(headers, 1)
  60. return db, blockchain, err
  61. }
  62. // newTestLightChain creates a LightChain that doesn't validate anything.
  63. func newTestLightChain() *LightChain {
  64. db := ethdb.NewMemDatabase()
  65. gspec := &core.Genesis{
  66. Difficulty: big.NewInt(1),
  67. Config: params.TestChainConfig,
  68. }
  69. gspec.MustCommit(db)
  70. lc, err := NewLightChain(&dummyOdr{db: db}, gspec.Config, ethash.NewFullFaker())
  71. if err != nil {
  72. panic(err)
  73. }
  74. return lc
  75. }
  76. // Test fork of length N starting from block i
  77. func testFork(t *testing.T, LightChain *LightChain, i, n int, comparator func(td1, td2 *big.Int)) {
  78. // Copy old chain up to #i into a new db
  79. db, LightChain2, err := newCanonical(i)
  80. if err != nil {
  81. t.Fatal("could not make new canonical in testFork", err)
  82. }
  83. // Assert the chains have the same header/block at #i
  84. var hash1, hash2 common.Hash
  85. hash1 = LightChain.GetHeaderByNumber(uint64(i)).Hash()
  86. hash2 = LightChain2.GetHeaderByNumber(uint64(i)).Hash()
  87. if hash1 != hash2 {
  88. t.Errorf("chain content mismatch at %d: have hash %v, want hash %v", i, hash2, hash1)
  89. }
  90. // Extend the newly created chain
  91. headerChainB := makeHeaderChain(LightChain2.CurrentHeader(), n, db, forkSeed)
  92. if _, err := LightChain2.InsertHeaderChain(headerChainB, 1); err != nil {
  93. t.Fatalf("failed to insert forking chain: %v", err)
  94. }
  95. // Sanity check that the forked chain can be imported into the original
  96. var tdPre, tdPost *big.Int
  97. tdPre = LightChain.GetTdByHash(LightChain.CurrentHeader().Hash())
  98. if err := testHeaderChainImport(headerChainB, LightChain); err != nil {
  99. t.Fatalf("failed to import forked header chain: %v", err)
  100. }
  101. tdPost = LightChain.GetTdByHash(headerChainB[len(headerChainB)-1].Hash())
  102. // Compare the total difficulties of the chains
  103. comparator(tdPre, tdPost)
  104. }
  105. // testHeaderChainImport tries to process a chain of header, writing them into
  106. // the database if successful.
  107. func testHeaderChainImport(chain []*types.Header, lightchain *LightChain) error {
  108. for _, header := range chain {
  109. // Try and validate the header
  110. if err := lightchain.engine.VerifyHeader(lightchain.hc, header, true); err != nil {
  111. return err
  112. }
  113. // Manually insert the header into the database, but don't reorganize (allows subsequent testing)
  114. lightchain.mu.Lock()
  115. rawdb.WriteTd(lightchain.chainDb, header.Hash(), header.Number.Uint64(), new(big.Int).Add(header.Difficulty, lightchain.GetTdByHash(header.ParentHash)))
  116. rawdb.WriteHeader(lightchain.chainDb, header)
  117. lightchain.mu.Unlock()
  118. }
  119. return nil
  120. }
  121. // Tests that given a starting canonical chain of a given size, it can be extended
  122. // with various length chains.
  123. func TestExtendCanonicalHeaders(t *testing.T) {
  124. length := 5
  125. // Make first chain starting from genesis
  126. _, processor, err := newCanonical(length)
  127. if err != nil {
  128. t.Fatalf("failed to make new canonical chain: %v", err)
  129. }
  130. // Define the difficulty comparator
  131. better := func(td1, td2 *big.Int) {
  132. if td2.Cmp(td1) <= 0 {
  133. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  134. }
  135. }
  136. // Start fork from current height
  137. testFork(t, processor, length, 1, better)
  138. testFork(t, processor, length, 2, better)
  139. testFork(t, processor, length, 5, better)
  140. testFork(t, processor, length, 10, better)
  141. }
  142. // Tests that given a starting canonical chain of a given size, creating shorter
  143. // forks do not take canonical ownership.
  144. func TestShorterForkHeaders(t *testing.T) {
  145. length := 10
  146. // Make first chain starting from genesis
  147. _, processor, err := newCanonical(length)
  148. if err != nil {
  149. t.Fatalf("failed to make new canonical chain: %v", err)
  150. }
  151. // Define the difficulty comparator
  152. worse := func(td1, td2 *big.Int) {
  153. if td2.Cmp(td1) >= 0 {
  154. t.Errorf("total difficulty mismatch: have %v, expected less than %v", td2, td1)
  155. }
  156. }
  157. // Sum of numbers must be less than `length` for this to be a shorter fork
  158. testFork(t, processor, 0, 3, worse)
  159. testFork(t, processor, 0, 7, worse)
  160. testFork(t, processor, 1, 1, worse)
  161. testFork(t, processor, 1, 7, worse)
  162. testFork(t, processor, 5, 3, worse)
  163. testFork(t, processor, 5, 4, worse)
  164. }
  165. // Tests that given a starting canonical chain of a given size, creating longer
  166. // forks do take canonical ownership.
  167. func TestLongerForkHeaders(t *testing.T) {
  168. length := 10
  169. // Make first chain starting from genesis
  170. _, processor, err := newCanonical(length)
  171. if err != nil {
  172. t.Fatalf("failed to make new canonical chain: %v", err)
  173. }
  174. // Define the difficulty comparator
  175. better := func(td1, td2 *big.Int) {
  176. if td2.Cmp(td1) <= 0 {
  177. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  178. }
  179. }
  180. // Sum of numbers must be greater than `length` for this to be a longer fork
  181. testFork(t, processor, 0, 11, better)
  182. testFork(t, processor, 0, 15, better)
  183. testFork(t, processor, 1, 10, better)
  184. testFork(t, processor, 1, 12, better)
  185. testFork(t, processor, 5, 6, better)
  186. testFork(t, processor, 5, 8, better)
  187. }
  188. // Tests that given a starting canonical chain of a given size, creating equal
  189. // forks do take canonical ownership.
  190. func TestEqualForkHeaders(t *testing.T) {
  191. length := 10
  192. // Make first chain starting from genesis
  193. _, processor, err := newCanonical(length)
  194. if err != nil {
  195. t.Fatalf("failed to make new canonical chain: %v", err)
  196. }
  197. // Define the difficulty comparator
  198. equal := func(td1, td2 *big.Int) {
  199. if td2.Cmp(td1) != 0 {
  200. t.Errorf("total difficulty mismatch: have %v, want %v", td2, td1)
  201. }
  202. }
  203. // Sum of numbers must be equal to `length` for this to be an equal fork
  204. testFork(t, processor, 0, 10, equal)
  205. testFork(t, processor, 1, 9, equal)
  206. testFork(t, processor, 2, 8, equal)
  207. testFork(t, processor, 5, 5, equal)
  208. testFork(t, processor, 6, 4, equal)
  209. testFork(t, processor, 9, 1, equal)
  210. }
  211. // Tests that chains missing links do not get accepted by the processor.
  212. func TestBrokenHeaderChain(t *testing.T) {
  213. // Make chain starting from genesis
  214. db, LightChain, err := newCanonical(10)
  215. if err != nil {
  216. t.Fatalf("failed to make new canonical chain: %v", err)
  217. }
  218. // Create a forked chain, and try to insert with a missing link
  219. chain := makeHeaderChain(LightChain.CurrentHeader(), 5, db, forkSeed)[1:]
  220. if err := testHeaderChainImport(chain, LightChain); err == nil {
  221. t.Errorf("broken header chain not reported")
  222. }
  223. }
  224. func makeHeaderChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Header {
  225. var chain []*types.Header
  226. for i, difficulty := range d {
  227. header := &types.Header{
  228. Coinbase: common.Address{seed},
  229. Number: big.NewInt(int64(i + 1)),
  230. Difficulty: big.NewInt(int64(difficulty)),
  231. UncleHash: types.EmptyUncleHash,
  232. TxHash: types.EmptyRootHash,
  233. ReceiptHash: types.EmptyRootHash,
  234. }
  235. if i == 0 {
  236. header.ParentHash = genesis.Hash()
  237. } else {
  238. header.ParentHash = chain[i-1].Hash()
  239. }
  240. chain = append(chain, types.CopyHeader(header))
  241. }
  242. return chain
  243. }
  244. type dummyOdr struct {
  245. OdrBackend
  246. db ethdb.Database
  247. }
  248. func (odr *dummyOdr) Database() ethdb.Database {
  249. return odr.db
  250. }
  251. func (odr *dummyOdr) Retrieve(ctx context.Context, req OdrRequest) error {
  252. return nil
  253. }
  254. // Tests that reorganizing a long difficult chain after a short easy one
  255. // overwrites the canonical numbers and links in the database.
  256. func TestReorgLongHeaders(t *testing.T) {
  257. testReorg(t, []int{1, 2, 4}, []int{1, 2, 3, 4}, 10)
  258. }
  259. // Tests that reorganizing a short difficult chain after a long easy one
  260. // overwrites the canonical numbers and links in the database.
  261. func TestReorgShortHeaders(t *testing.T) {
  262. testReorg(t, []int{1, 2, 3, 4}, []int{1, 10}, 11)
  263. }
  264. func testReorg(t *testing.T, first, second []int, td int64) {
  265. bc := newTestLightChain()
  266. // Insert an easy and a difficult chain afterwards
  267. bc.InsertHeaderChain(makeHeaderChainWithDiff(bc.genesisBlock, first, 11), 1)
  268. bc.InsertHeaderChain(makeHeaderChainWithDiff(bc.genesisBlock, second, 22), 1)
  269. // Check that the chain is valid number and link wise
  270. prev := bc.CurrentHeader()
  271. for header := bc.GetHeaderByNumber(bc.CurrentHeader().Number.Uint64() - 1); header.Number.Uint64() != 0; prev, header = header, bc.GetHeaderByNumber(header.Number.Uint64()-1) {
  272. if prev.ParentHash != header.Hash() {
  273. t.Errorf("parent header hash mismatch: have %x, want %x", prev.ParentHash, header.Hash())
  274. }
  275. }
  276. // Make sure the chain total difficulty is the correct one
  277. want := new(big.Int).Add(bc.genesisBlock.Difficulty(), big.NewInt(td))
  278. if have := bc.GetTdByHash(bc.CurrentHeader().Hash()); have.Cmp(want) != 0 {
  279. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  280. }
  281. }
  282. // Tests that the insertion functions detect banned hashes.
  283. func TestBadHeaderHashes(t *testing.T) {
  284. bc := newTestLightChain()
  285. // Create a chain, ban a hash and try to import
  286. var err error
  287. headers := makeHeaderChainWithDiff(bc.genesisBlock, []int{1, 2, 4}, 10)
  288. core.BadHashes[headers[2].Hash()] = true
  289. if _, err = bc.InsertHeaderChain(headers, 1); err != core.ErrBlacklistedHash {
  290. t.Errorf("error mismatch: have: %v, want %v", err, core.ErrBlacklistedHash)
  291. }
  292. }
  293. // Tests that bad hashes are detected on boot, and the chan rolled back to a
  294. // good state prior to the bad hash.
  295. func TestReorgBadHeaderHashes(t *testing.T) {
  296. bc := newTestLightChain()
  297. // Create a chain, import and ban aferwards
  298. headers := makeHeaderChainWithDiff(bc.genesisBlock, []int{1, 2, 3, 4}, 10)
  299. if _, err := bc.InsertHeaderChain(headers, 1); err != nil {
  300. t.Fatalf("failed to import headers: %v", err)
  301. }
  302. if bc.CurrentHeader().Hash() != headers[3].Hash() {
  303. t.Errorf("last header hash mismatch: have: %x, want %x", bc.CurrentHeader().Hash(), headers[3].Hash())
  304. }
  305. core.BadHashes[headers[3].Hash()] = true
  306. defer func() { delete(core.BadHashes, headers[3].Hash()) }()
  307. // Create a new LightChain and check that it rolled back the state.
  308. ncm, err := NewLightChain(&dummyOdr{db: bc.chainDb}, params.TestChainConfig, ethash.NewFaker())
  309. if err != nil {
  310. t.Fatalf("failed to create new chain manager: %v", err)
  311. }
  312. if ncm.CurrentHeader().Hash() != headers[2].Hash() {
  313. t.Errorf("last header hash mismatch: have: %x, want %x", ncm.CurrentHeader().Hash(), headers[2].Hash())
  314. }
  315. }