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