lightchain_test.go 13 KB

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