testchain_test.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/consensus/ethash"
  23. "github.com/ethereum/go-ethereum/core"
  24. "github.com/ethereum/go-ethereum/core/rawdb"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/params"
  28. )
  29. // Test chain parameters.
  30. var (
  31. testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  32. testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
  33. testDB = rawdb.NewMemoryDatabase()
  34. gspec = core.Genesis{
  35. Alloc: core.GenesisAlloc{testAddress: {Balance: big.NewInt(1000000000000000)}},
  36. BaseFee: big.NewInt(params.InitialBaseFee),
  37. }
  38. testGenesis = gspec.MustCommit(testDB)
  39. )
  40. // The common prefix of all test chains:
  41. var testChainBase = newTestChain(blockCacheMaxItems+200, testGenesis)
  42. // Different forks on top of the base chain:
  43. var testChainForkLightA, testChainForkLightB, testChainForkHeavy *testChain
  44. func init() {
  45. var forkLen = int(fullMaxForkAncestry + 50)
  46. var wg sync.WaitGroup
  47. wg.Add(3)
  48. go func() { testChainForkLightA = testChainBase.makeFork(forkLen, false, 1); wg.Done() }()
  49. go func() { testChainForkLightB = testChainBase.makeFork(forkLen, false, 2); wg.Done() }()
  50. go func() { testChainForkHeavy = testChainBase.makeFork(forkLen, true, 3); wg.Done() }()
  51. wg.Wait()
  52. }
  53. type testChain struct {
  54. genesis *types.Block
  55. chain []common.Hash
  56. headerm map[common.Hash]*types.Header
  57. blockm map[common.Hash]*types.Block
  58. receiptm map[common.Hash][]*types.Receipt
  59. tdm map[common.Hash]*big.Int
  60. }
  61. // newTestChain creates a blockchain of the given length.
  62. func newTestChain(length int, genesis *types.Block) *testChain {
  63. tc := new(testChain).copy(length)
  64. tc.genesis = genesis
  65. tc.chain = append(tc.chain, genesis.Hash())
  66. tc.headerm[tc.genesis.Hash()] = tc.genesis.Header()
  67. tc.tdm[tc.genesis.Hash()] = tc.genesis.Difficulty()
  68. tc.blockm[tc.genesis.Hash()] = tc.genesis
  69. tc.generate(length-1, 0, genesis, false)
  70. return tc
  71. }
  72. // makeFork creates a fork on top of the test chain.
  73. func (tc *testChain) makeFork(length int, heavy bool, seed byte) *testChain {
  74. fork := tc.copy(tc.len() + length)
  75. fork.generate(length, seed, tc.headBlock(), heavy)
  76. return fork
  77. }
  78. // shorten creates a copy of the chain with the given length. It panics if the
  79. // length is longer than the number of available blocks.
  80. func (tc *testChain) shorten(length int) *testChain {
  81. if length > tc.len() {
  82. panic(fmt.Errorf("can't shorten test chain to %d blocks, it's only %d blocks long", length, tc.len()))
  83. }
  84. return tc.copy(length)
  85. }
  86. func (tc *testChain) copy(newlen int) *testChain {
  87. cpy := &testChain{
  88. genesis: tc.genesis,
  89. headerm: make(map[common.Hash]*types.Header, newlen),
  90. blockm: make(map[common.Hash]*types.Block, newlen),
  91. receiptm: make(map[common.Hash][]*types.Receipt, newlen),
  92. tdm: make(map[common.Hash]*big.Int, newlen),
  93. }
  94. for i := 0; i < len(tc.chain) && i < newlen; i++ {
  95. hash := tc.chain[i]
  96. cpy.chain = append(cpy.chain, tc.chain[i])
  97. cpy.tdm[hash] = tc.tdm[hash]
  98. cpy.blockm[hash] = tc.blockm[hash]
  99. cpy.headerm[hash] = tc.headerm[hash]
  100. cpy.receiptm[hash] = tc.receiptm[hash]
  101. }
  102. return cpy
  103. }
  104. // generate creates a chain of n blocks starting at and including parent.
  105. // the returned hash chain is ordered head->parent. In addition, every 22th block
  106. // contains a transaction and every 5th an uncle to allow testing correct block
  107. // reassembly.
  108. func (tc *testChain) generate(n int, seed byte, parent *types.Block, heavy bool) {
  109. // start := time.Now()
  110. // defer func() { fmt.Printf("test chain generated in %v\n", time.Since(start)) }()
  111. blocks, receipts := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), testDB, n, func(i int, block *core.BlockGen) {
  112. block.SetCoinbase(common.Address{seed})
  113. // If a heavy chain is requested, delay blocks to raise difficulty
  114. if heavy {
  115. block.OffsetTime(-1)
  116. }
  117. // Include transactions to the miner to make blocks more interesting.
  118. if parent == tc.genesis && i%22 == 0 {
  119. signer := types.MakeSigner(params.TestChainConfig, block.Number())
  120. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, block.BaseFee(), nil), signer, testKey)
  121. if err != nil {
  122. panic(err)
  123. }
  124. block.AddTx(tx)
  125. }
  126. // if the block number is a multiple of 5, add a bonus uncle to the block
  127. if i > 0 && i%5 == 0 {
  128. block.AddUncle(&types.Header{
  129. ParentHash: block.PrevBlock(i - 1).Hash(),
  130. Number: big.NewInt(block.Number().Int64() - 1),
  131. })
  132. }
  133. })
  134. // Convert the block-chain into a hash-chain and header/block maps
  135. td := new(big.Int).Set(tc.td(parent.Hash()))
  136. for i, b := range blocks {
  137. td := td.Add(td, b.Difficulty())
  138. hash := b.Hash()
  139. tc.chain = append(tc.chain, hash)
  140. tc.blockm[hash] = b
  141. tc.headerm[hash] = b.Header()
  142. tc.receiptm[hash] = receipts[i]
  143. tc.tdm[hash] = new(big.Int).Set(td)
  144. }
  145. }
  146. // len returns the total number of blocks in the chain.
  147. func (tc *testChain) len() int {
  148. return len(tc.chain)
  149. }
  150. // headBlock returns the head of the chain.
  151. func (tc *testChain) headBlock() *types.Block {
  152. return tc.blockm[tc.chain[len(tc.chain)-1]]
  153. }
  154. // td returns the total difficulty of the given block.
  155. func (tc *testChain) td(hash common.Hash) *big.Int {
  156. return tc.tdm[hash]
  157. }
  158. // headersByHash returns headers in order from the given hash.
  159. func (tc *testChain) headersByHash(origin common.Hash, amount int, skip int, reverse bool) []*types.Header {
  160. num, _ := tc.hashToNumber(origin)
  161. return tc.headersByNumber(num, amount, skip, reverse)
  162. }
  163. // headersByNumber returns headers from the given number.
  164. func (tc *testChain) headersByNumber(origin uint64, amount int, skip int, reverse bool) []*types.Header {
  165. result := make([]*types.Header, 0, amount)
  166. if !reverse {
  167. for num := origin; num < uint64(len(tc.chain)) && len(result) < amount; num += uint64(skip) + 1 {
  168. if header, ok := tc.headerm[tc.chain[int(num)]]; ok {
  169. result = append(result, header)
  170. }
  171. }
  172. } else {
  173. for num := int64(origin); num >= 0 && len(result) < amount; num -= int64(skip) + 1 {
  174. if header, ok := tc.headerm[tc.chain[int(num)]]; ok {
  175. result = append(result, header)
  176. }
  177. }
  178. }
  179. return result
  180. }
  181. // receipts returns the receipts of the given block hashes.
  182. func (tc *testChain) receipts(hashes []common.Hash) [][]*types.Receipt {
  183. results := make([][]*types.Receipt, 0, len(hashes))
  184. for _, hash := range hashes {
  185. if receipt, ok := tc.receiptm[hash]; ok {
  186. results = append(results, receipt)
  187. }
  188. }
  189. return results
  190. }
  191. // bodies returns the block bodies of the given block hashes.
  192. func (tc *testChain) bodies(hashes []common.Hash) ([][]*types.Transaction, [][]*types.Header) {
  193. transactions := make([][]*types.Transaction, 0, len(hashes))
  194. uncles := make([][]*types.Header, 0, len(hashes))
  195. for _, hash := range hashes {
  196. if block, ok := tc.blockm[hash]; ok {
  197. transactions = append(transactions, block.Transactions())
  198. uncles = append(uncles, block.Uncles())
  199. }
  200. }
  201. return transactions, uncles
  202. }
  203. func (tc *testChain) hashToNumber(target common.Hash) (uint64, bool) {
  204. for num, hash := range tc.chain {
  205. if hash == target {
  206. return uint64(num), true
  207. }
  208. }
  209. return 0, false
  210. }