lightchain_test.go 12 KB

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