lightchain_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. "fmt"
  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/types"
  26. "github.com/ethereum/go-ethereum/ethdb"
  27. "github.com/ethereum/go-ethereum/event"
  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), 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, _ := ethdb.NewMemDatabase()
  51. gspec := core.Genesis{Config: params.TestChainConfig}
  52. genesis := gspec.MustCommit(db)
  53. blockchain, _ := NewLightChain(&dummyOdr{db: db}, gspec.Config, ethash.NewFaker(), new(event.TypeMux))
  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, _ := ethdb.NewMemDatabase()
  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(), new(event.TypeMux))
  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. var (
  93. headerChainB []*types.Header
  94. )
  95. headerChainB = makeHeaderChain(LightChain2.CurrentHeader(), n, db, forkSeed)
  96. if _, err := LightChain2.InsertHeaderChain(headerChainB, 1); err != nil {
  97. t.Fatalf("failed to insert forking chain: %v", err)
  98. }
  99. // Sanity check that the forked chain can be imported into the original
  100. var tdPre, tdPost *big.Int
  101. tdPre = LightChain.GetTdByHash(LightChain.CurrentHeader().Hash())
  102. if err := testHeaderChainImport(headerChainB, LightChain); err != nil {
  103. t.Fatalf("failed to import forked header chain: %v", err)
  104. }
  105. tdPost = LightChain.GetTdByHash(headerChainB[len(headerChainB)-1].Hash())
  106. // Compare the total difficulties of the chains
  107. comparator(tdPre, tdPost)
  108. }
  109. func printChain(bc *LightChain) {
  110. for i := bc.CurrentHeader().Number.Uint64(); i > 0; i-- {
  111. b := bc.GetHeaderByNumber(uint64(i))
  112. fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty)
  113. }
  114. }
  115. // testHeaderChainImport tries to process a chain of header, writing them into
  116. // the database if successful.
  117. func testHeaderChainImport(chain []*types.Header, lightchain *LightChain) error {
  118. for _, header := range chain {
  119. // Try and validate the header
  120. if err := lightchain.engine.VerifyHeader(lightchain.hc, header, true); err != nil {
  121. return err
  122. }
  123. // Manually insert the header into the database, but don't reorganize (allows subsequent testing)
  124. lightchain.mu.Lock()
  125. core.WriteTd(lightchain.chainDb, header.Hash(), header.Number.Uint64(), new(big.Int).Add(header.Difficulty, lightchain.GetTdByHash(header.ParentHash)))
  126. core.WriteHeader(lightchain.chainDb, header)
  127. lightchain.mu.Unlock()
  128. }
  129. return nil
  130. }
  131. // Tests that given a starting canonical chain of a given size, it can be extended
  132. // with various length chains.
  133. func TestExtendCanonicalHeaders(t *testing.T) {
  134. length := 5
  135. // Make first chain starting from genesis
  136. _, processor, err := newCanonical(length)
  137. if err != nil {
  138. t.Fatalf("failed to make new canonical chain: %v", err)
  139. }
  140. // Define the difficulty comparator
  141. better := func(td1, td2 *big.Int) {
  142. if td2.Cmp(td1) <= 0 {
  143. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  144. }
  145. }
  146. // Start fork from current height
  147. testFork(t, processor, length, 1, better)
  148. testFork(t, processor, length, 2, better)
  149. testFork(t, processor, length, 5, better)
  150. testFork(t, processor, length, 10, better)
  151. }
  152. // Tests that given a starting canonical chain of a given size, creating shorter
  153. // forks do not take canonical ownership.
  154. func TestShorterForkHeaders(t *testing.T) {
  155. length := 10
  156. // Make first chain starting from genesis
  157. _, processor, err := newCanonical(length)
  158. if err != nil {
  159. t.Fatalf("failed to make new canonical chain: %v", err)
  160. }
  161. // Define the difficulty comparator
  162. worse := func(td1, td2 *big.Int) {
  163. if td2.Cmp(td1) >= 0 {
  164. t.Errorf("total difficulty mismatch: have %v, expected less than %v", td2, td1)
  165. }
  166. }
  167. // Sum of numbers must be less than `length` for this to be a shorter fork
  168. testFork(t, processor, 0, 3, worse)
  169. testFork(t, processor, 0, 7, worse)
  170. testFork(t, processor, 1, 1, worse)
  171. testFork(t, processor, 1, 7, worse)
  172. testFork(t, processor, 5, 3, worse)
  173. testFork(t, processor, 5, 4, worse)
  174. }
  175. // Tests that given a starting canonical chain of a given size, creating longer
  176. // forks do take canonical ownership.
  177. func TestLongerForkHeaders(t *testing.T) {
  178. length := 10
  179. // Make first chain starting from genesis
  180. _, processor, err := newCanonical(length)
  181. if err != nil {
  182. t.Fatalf("failed to make new canonical chain: %v", err)
  183. }
  184. // Define the difficulty comparator
  185. better := func(td1, td2 *big.Int) {
  186. if td2.Cmp(td1) <= 0 {
  187. t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
  188. }
  189. }
  190. // Sum of numbers must be greater than `length` for this to be a longer fork
  191. testFork(t, processor, 0, 11, better)
  192. testFork(t, processor, 0, 15, better)
  193. testFork(t, processor, 1, 10, better)
  194. testFork(t, processor, 1, 12, better)
  195. testFork(t, processor, 5, 6, better)
  196. testFork(t, processor, 5, 8, better)
  197. }
  198. // Tests that given a starting canonical chain of a given size, creating equal
  199. // forks do take canonical ownership.
  200. func TestEqualForkHeaders(t *testing.T) {
  201. length := 10
  202. // Make first chain starting from genesis
  203. _, processor, err := newCanonical(length)
  204. if err != nil {
  205. t.Fatalf("failed to make new canonical chain: %v", err)
  206. }
  207. // Define the difficulty comparator
  208. equal := func(td1, td2 *big.Int) {
  209. if td2.Cmp(td1) != 0 {
  210. t.Errorf("total difficulty mismatch: have %v, want %v", td2, td1)
  211. }
  212. }
  213. // Sum of numbers must be equal to `length` for this to be an equal fork
  214. testFork(t, processor, 0, 10, equal)
  215. testFork(t, processor, 1, 9, equal)
  216. testFork(t, processor, 2, 8, equal)
  217. testFork(t, processor, 5, 5, equal)
  218. testFork(t, processor, 6, 4, equal)
  219. testFork(t, processor, 9, 1, equal)
  220. }
  221. // Tests that chains missing links do not get accepted by the processor.
  222. func TestBrokenHeaderChain(t *testing.T) {
  223. // Make chain starting from genesis
  224. db, LightChain, err := newCanonical(10)
  225. if err != nil {
  226. t.Fatalf("failed to make new canonical chain: %v", err)
  227. }
  228. // Create a forked chain, and try to insert with a missing link
  229. chain := makeHeaderChain(LightChain.CurrentHeader(), 5, db, forkSeed)[1:]
  230. if err := testHeaderChainImport(chain, LightChain); err == nil {
  231. t.Errorf("broken header chain not reported")
  232. }
  233. }
  234. func makeHeaderChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Header {
  235. var chain []*types.Header
  236. for i, difficulty := range d {
  237. header := &types.Header{
  238. Coinbase: common.Address{seed},
  239. Number: big.NewInt(int64(i + 1)),
  240. Difficulty: big.NewInt(int64(difficulty)),
  241. UncleHash: types.EmptyUncleHash,
  242. TxHash: types.EmptyRootHash,
  243. ReceiptHash: types.EmptyRootHash,
  244. }
  245. if i == 0 {
  246. header.ParentHash = genesis.Hash()
  247. } else {
  248. header.ParentHash = chain[i-1].Hash()
  249. }
  250. chain = append(chain, types.CopyHeader(header))
  251. }
  252. return chain
  253. }
  254. type dummyOdr struct {
  255. OdrBackend
  256. db ethdb.Database
  257. }
  258. func (odr *dummyOdr) Database() ethdb.Database {
  259. return odr.db
  260. }
  261. func (odr *dummyOdr) Retrieve(ctx context.Context, req OdrRequest) error {
  262. return nil
  263. }
  264. // Tests that reorganizing a long difficult chain after a short easy one
  265. // overwrites the canonical numbers and links in the database.
  266. func TestReorgLongHeaders(t *testing.T) {
  267. testReorg(t, []int{1, 2, 4}, []int{1, 2, 3, 4}, 10)
  268. }
  269. // Tests that reorganizing a short difficult chain after a long easy one
  270. // overwrites the canonical numbers and links in the database.
  271. func TestReorgShortHeaders(t *testing.T) {
  272. testReorg(t, []int{1, 2, 3, 4}, []int{1, 10}, 11)
  273. }
  274. func testReorg(t *testing.T, first, second []int, td int64) {
  275. bc := newTestLightChain()
  276. // Insert an easy and a difficult chain afterwards
  277. bc.InsertHeaderChain(makeHeaderChainWithDiff(bc.genesisBlock, first, 11), 1)
  278. bc.InsertHeaderChain(makeHeaderChainWithDiff(bc.genesisBlock, second, 22), 1)
  279. // Check that the chain is valid number and link wise
  280. prev := bc.CurrentHeader()
  281. for header := bc.GetHeaderByNumber(bc.CurrentHeader().Number.Uint64() - 1); header.Number.Uint64() != 0; prev, header = header, bc.GetHeaderByNumber(header.Number.Uint64()-1) {
  282. if prev.ParentHash != header.Hash() {
  283. t.Errorf("parent header hash mismatch: have %x, want %x", prev.ParentHash, header.Hash())
  284. }
  285. }
  286. // Make sure the chain total difficulty is the correct one
  287. want := new(big.Int).Add(bc.genesisBlock.Difficulty(), big.NewInt(td))
  288. if have := bc.GetTdByHash(bc.CurrentHeader().Hash()); have.Cmp(want) != 0 {
  289. t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
  290. }
  291. }
  292. // Tests that the insertion functions detect banned hashes.
  293. func TestBadHeaderHashes(t *testing.T) {
  294. bc := newTestLightChain()
  295. // Create a chain, ban a hash and try to import
  296. var err error
  297. headers := makeHeaderChainWithDiff(bc.genesisBlock, []int{1, 2, 4}, 10)
  298. core.BadHashes[headers[2].Hash()] = true
  299. _, err = bc.InsertHeaderChain(headers, 1)
  300. if !core.IsBadHashError(err) {
  301. t.Errorf("error mismatch: want: BadHashError, have: %v", err)
  302. }
  303. }
  304. // Tests that bad hashes are detected on boot, and the chan rolled back to a
  305. // good state prior to the bad hash.
  306. func TestReorgBadHeaderHashes(t *testing.T) {
  307. bc := newTestLightChain()
  308. // Create a chain, import and ban aferwards
  309. headers := makeHeaderChainWithDiff(bc.genesisBlock, []int{1, 2, 3, 4}, 10)
  310. if _, err := bc.InsertHeaderChain(headers, 1); err != nil {
  311. t.Fatalf("failed to import headers: %v", err)
  312. }
  313. if bc.CurrentHeader().Hash() != headers[3].Hash() {
  314. t.Errorf("last header hash mismatch: have: %x, want %x", bc.CurrentHeader().Hash(), headers[3].Hash())
  315. }
  316. core.BadHashes[headers[3].Hash()] = true
  317. defer func() { delete(core.BadHashes, headers[3].Hash()) }()
  318. // Create a new LightChain and check that it rolled back the state.
  319. ncm, err := NewLightChain(&dummyOdr{db: bc.chainDb}, params.TestChainConfig, ethash.NewFaker(), new(event.TypeMux))
  320. if err != nil {
  321. t.Fatalf("failed to create new chain manager: %v", err)
  322. }
  323. if ncm.CurrentHeader().Hash() != headers[2].Hash() {
  324. t.Errorf("last header hash mismatch: have: %x, want %x", ncm.CurrentHeader().Hash(), headers[2].Hash())
  325. }
  326. }