testchain_test.go 7.8 KB

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