lightchain_test.go 14 KB

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