testchain_test.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. // Copyright 2018 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 downloader
  17. import (
  18. "fmt"
  19. "math/big"
  20. "sync"
  21. "time"
  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/core/vm"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. "github.com/ethereum/go-ethereum/params"
  30. )
  31. // Test chain parameters.
  32. var (
  33. testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  34. testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
  35. testDB = rawdb.NewMemoryDatabase()
  36. testGspec = core.Genesis{
  37. Alloc: core.GenesisAlloc{testAddress: {Balance: big.NewInt(1000000000000000)}},
  38. BaseFee: big.NewInt(params.InitialBaseFee),
  39. }
  40. testGenesis = testGspec.MustCommit(testDB)
  41. )
  42. // The common prefix of all test chains:
  43. var testChainBase *testChain
  44. // Different forks on top of the base chain:
  45. var testChainForkLightA, testChainForkLightB, testChainForkHeavy *testChain
  46. var pregenerated bool
  47. func init() {
  48. // Reduce some of the parameters to make the tester faster
  49. fullMaxForkAncestry = 10000
  50. lightMaxForkAncestry = 10000
  51. blockCacheMaxItems = 1024
  52. fsHeaderSafetyNet = 256
  53. fsHeaderContCheck = 500 * time.Millisecond
  54. testChainBase = newTestChain(blockCacheMaxItems+200, testGenesis)
  55. var forkLen = int(fullMaxForkAncestry + 50)
  56. var wg sync.WaitGroup
  57. // Generate the test chains to seed the peers with
  58. wg.Add(3)
  59. go func() { testChainForkLightA = testChainBase.makeFork(forkLen, false, 1); wg.Done() }()
  60. go func() { testChainForkLightB = testChainBase.makeFork(forkLen, false, 2); wg.Done() }()
  61. go func() { testChainForkHeavy = testChainBase.makeFork(forkLen, true, 3); wg.Done() }()
  62. wg.Wait()
  63. // Generate the test peers used by the tests to avoid overloading during testing.
  64. // These seemingly random chains are used in various downloader tests. We're just
  65. // pre-generating them here.
  66. chains := []*testChain{
  67. testChainBase,
  68. testChainForkLightA,
  69. testChainForkLightB,
  70. testChainForkHeavy,
  71. testChainBase.shorten(1),
  72. testChainBase.shorten(blockCacheMaxItems - 15),
  73. testChainBase.shorten((blockCacheMaxItems - 15) / 2),
  74. testChainBase.shorten(blockCacheMaxItems - 15 - 5),
  75. testChainBase.shorten(MaxHeaderFetch),
  76. testChainBase.shorten(800),
  77. testChainBase.shorten(800 / 2),
  78. testChainBase.shorten(800 / 3),
  79. testChainBase.shorten(800 / 4),
  80. testChainBase.shorten(800 / 5),
  81. testChainBase.shorten(800 / 6),
  82. testChainBase.shorten(800 / 7),
  83. testChainBase.shorten(800 / 8),
  84. testChainBase.shorten(3*fsHeaderSafetyNet + 256 + fsMinFullBlocks),
  85. testChainBase.shorten(fsMinFullBlocks + 256 - 1),
  86. testChainForkLightA.shorten(len(testChainBase.blocks) + 80),
  87. testChainForkLightB.shorten(len(testChainBase.blocks) + 81),
  88. testChainForkLightA.shorten(len(testChainBase.blocks) + MaxHeaderFetch),
  89. testChainForkLightB.shorten(len(testChainBase.blocks) + MaxHeaderFetch),
  90. testChainForkHeavy.shorten(len(testChainBase.blocks) + 79),
  91. }
  92. wg.Add(len(chains))
  93. for _, chain := range chains {
  94. go func(blocks []*types.Block) {
  95. newTestBlockchain(blocks)
  96. wg.Done()
  97. }(chain.blocks[1:])
  98. }
  99. wg.Wait()
  100. // Mark the chains pregenerated. Generating a new one will lead to a panic.
  101. pregenerated = true
  102. }
  103. type testChain struct {
  104. blocks []*types.Block
  105. }
  106. // newTestChain creates a blockchain of the given length.
  107. func newTestChain(length int, genesis *types.Block) *testChain {
  108. tc := &testChain{
  109. blocks: []*types.Block{genesis},
  110. }
  111. tc.generate(length-1, 0, genesis, false)
  112. return tc
  113. }
  114. // makeFork creates a fork on top of the test chain.
  115. func (tc *testChain) makeFork(length int, heavy bool, seed byte) *testChain {
  116. fork := tc.copy(len(tc.blocks) + length)
  117. fork.generate(length, seed, tc.blocks[len(tc.blocks)-1], heavy)
  118. return fork
  119. }
  120. // shorten creates a copy of the chain with the given length. It panics if the
  121. // length is longer than the number of available blocks.
  122. func (tc *testChain) shorten(length int) *testChain {
  123. if length > len(tc.blocks) {
  124. panic(fmt.Errorf("can't shorten test chain to %d blocks, it's only %d blocks long", length, len(tc.blocks)))
  125. }
  126. return tc.copy(length)
  127. }
  128. func (tc *testChain) copy(newlen int) *testChain {
  129. if newlen > len(tc.blocks) {
  130. newlen = len(tc.blocks)
  131. }
  132. cpy := &testChain{
  133. blocks: append([]*types.Block{}, tc.blocks[:newlen]...),
  134. }
  135. return cpy
  136. }
  137. // generate creates a chain of n blocks starting at and including parent.
  138. // the returned hash chain is ordered head->parent. In addition, every 22th block
  139. // contains a transaction and every 5th an uncle to allow testing correct block
  140. // reassembly.
  141. func (tc *testChain) generate(n int, seed byte, parent *types.Block, heavy bool) {
  142. blocks, _ := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), testDB, n, func(i int, block *core.BlockGen) {
  143. block.SetCoinbase(common.Address{seed})
  144. // If a heavy chain is requested, delay blocks to raise difficulty
  145. if heavy {
  146. block.OffsetTime(-9)
  147. }
  148. // Include transactions to the miner to make blocks more interesting.
  149. if parent == tc.blocks[0] && i%22 == 0 {
  150. signer := types.MakeSigner(params.TestChainConfig, block.Number())
  151. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, block.BaseFee(), nil), signer, testKey)
  152. if err != nil {
  153. panic(err)
  154. }
  155. block.AddTx(tx)
  156. }
  157. // if the block number is a multiple of 5, add a bonus uncle to the block
  158. if i > 0 && i%5 == 0 {
  159. block.AddUncle(&types.Header{
  160. ParentHash: block.PrevBlock(i - 2).Hash(),
  161. Number: big.NewInt(block.Number().Int64() - 1),
  162. })
  163. }
  164. })
  165. tc.blocks = append(tc.blocks, blocks...)
  166. }
  167. var (
  168. testBlockchains = make(map[common.Hash]*testBlockchain)
  169. testBlockchainsLock sync.Mutex
  170. )
  171. type testBlockchain struct {
  172. chain *core.BlockChain
  173. gen sync.Once
  174. }
  175. // newTestBlockchain creates a blockchain database built by running the given blocks,
  176. // either actually running them, or reusing a previously created one. The returned
  177. // chains are *shared*, so *do not* mutate them.
  178. func newTestBlockchain(blocks []*types.Block) *core.BlockChain {
  179. // Retrieve an existing database, or create a new one
  180. head := testGenesis.Hash()
  181. if len(blocks) > 0 {
  182. head = blocks[len(blocks)-1].Hash()
  183. }
  184. testBlockchainsLock.Lock()
  185. if _, ok := testBlockchains[head]; !ok {
  186. testBlockchains[head] = new(testBlockchain)
  187. }
  188. tbc := testBlockchains[head]
  189. testBlockchainsLock.Unlock()
  190. // Ensure that the database is generated
  191. tbc.gen.Do(func() {
  192. if pregenerated {
  193. panic("Requested chain generation outside of init")
  194. }
  195. db := rawdb.NewMemoryDatabase()
  196. testGspec.MustCommit(db)
  197. chain, err := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
  198. if err != nil {
  199. panic(err)
  200. }
  201. if n, err := chain.InsertChain(blocks); err != nil {
  202. panic(fmt.Sprintf("block %d: %v", n, err))
  203. }
  204. tbc.chain = chain
  205. })
  206. return tbc.chain
  207. }