github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/core/chain_makers.go (about) 1 package core 2 3 import ( 4 "fmt" 5 "math/big" 6 7 "github.com/quickchainproject/quickchain/common" 8 "github.com/quickchainproject/quickchain/consensus" 9 "github.com/quickchainproject/quickchain/consensus/misc" 10 "github.com/quickchainproject/quickchain/core/state" 11 "github.com/quickchainproject/quickchain/core/types" 12 "github.com/quickchainproject/quickchain/core/vm" 13 "github.com/quickchainproject/quickchain/qctdb" 14 "github.com/quickchainproject/quickchain/params" 15 ) 16 17 // So we can deterministically seed different blockchains 18 var ( 19 canonicalSeed = 1 20 forkSeed = 2 21 ) 22 23 // BlockGen creates blocks for testing. 24 // See GenerateChain for a detailed explanation. 25 type BlockGen struct { 26 i int 27 parent *types.Block 28 chain []*types.Block 29 chainReader consensus.ChainReader 30 header *types.Header 31 statedb *state.StateDB 32 33 gasPool *GasPool 34 txs []*types.Transaction 35 receipts []*types.Receipt 36 uncles []*types.Header 37 38 config *params.ChainConfig 39 engine consensus.Engine 40 } 41 42 // SetCoinbase sets the coinbase of the generated block. 43 // It can be called at most once. 44 func (b *BlockGen) SetCoinbase(addr common.Address) { 45 if b.gasPool != nil { 46 if len(b.txs) > 0 { 47 panic("coinbase must be set before adding transactions") 48 } 49 panic("coinbase can only be set once") 50 } 51 b.header.Coinbase = addr 52 b.gasPool = new(GasPool).AddGas(b.header.GasLimit) 53 } 54 55 // SetExtra sets the extra data field of the generated block. 56 func (b *BlockGen) SetExtra(data []byte) { 57 b.header.Extra = data 58 } 59 60 // AddTx adds a transaction to the generated block. If no coinbase has 61 // been set, the block's coinbase is set to the zero address. 62 // 63 // AddTx panics if the transaction cannot be executed. In addition to 64 // the protocol-imposed limitations (gas limit, etc.), there are some 65 // further limitations on the content of transactions that can be 66 // added. Notably, contract code relying on the BLOCKHASH instruction 67 // will panic during execution. 68 func (b *BlockGen) AddTx(tx *types.Transaction) { 69 b.AddTxWithChain(nil, tx) 70 } 71 72 // AddTxWithChain adds a transaction to the generated block. If no coinbase has 73 // been set, the block's coinbase is set to the zero address. 74 // 75 // AddTxWithChain panics if the transaction cannot be executed. In addition to 76 // the protocol-imposed limitations (gas limit, etc.), there are some 77 // further limitations on the content of transactions that can be 78 // added. If contract code relies on the BLOCKHASH instruction, 79 // the block in chain will be returned. 80 func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) { 81 if b.gasPool == nil { 82 b.SetCoinbase(common.Address{}) 83 } 84 b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs)) 85 receipt, _, err := ApplyTransaction(b.config, nil, bc, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, &b.header.GasUsed, vm.Config{}) 86 if err != nil { 87 panic(err) 88 } 89 b.txs = append(b.txs, tx) 90 b.receipts = append(b.receipts, receipt) 91 } 92 93 // Number returns the block number of the block being generated. 94 func (b *BlockGen) Number() *big.Int { 95 return new(big.Int).Set(b.header.Number) 96 } 97 98 // AddUncheckedReceipt forcefully adds a receipts to the block without a 99 // backing transaction. 100 // 101 // AddUncheckedReceipt will cause consensus failures when used during real 102 // chain processing. This is best used in conjunction with raw block insertion. 103 func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) { 104 b.receipts = append(b.receipts, receipt) 105 } 106 107 // TxNonce returns the next valid transaction nonce for the 108 // account at addr. It panics if the account does not exist. 109 func (b *BlockGen) TxNonce(addr common.Address) uint64 { 110 if !b.statedb.Exist(addr) { 111 panic("account does not exist") 112 } 113 return b.statedb.GetNonce(addr) 114 } 115 116 // AddUncle adds an uncle header to the generated block. 117 func (b *BlockGen) AddUncle(h *types.Header) { 118 b.uncles = append(b.uncles, h) 119 } 120 121 // PrevBlock returns a previously generated block by number. It panics if 122 // num is greater or equal to the number of the block being generated. 123 // For index -1, PrevBlock returns the parent block given to GenerateChain. 124 func (b *BlockGen) PrevBlock(index int) *types.Block { 125 if index >= b.i { 126 panic("block index out of range") 127 } 128 if index == -1 { 129 return b.parent 130 } 131 return b.chain[index] 132 } 133 134 // OffsetTime modifies the time instance of a block, implicitly changing its 135 // associated difficulty. It's useful to test scenarios where forking is not 136 // tied to chain length directly. 137 func (b *BlockGen) OffsetTime(seconds int64) { 138 b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds)) 139 if b.header.Time.Cmp(b.parent.Header().Time) <= 0 { 140 panic("block time out of range") 141 } 142 b.header.Difficulty = b.engine.CalcDifficulty(b.chainReader, b.header.Time.Uint64(), b.parent.Header()) 143 } 144 145 // GenerateChain creates a chain of n blocks. The first block's 146 // parent will be the provided parent. db is used to store 147 // intermediate states and should contain the parent's state trie. 148 // 149 // The generator function is called with a new block generator for 150 // every block. Any transactions and uncles added to the generator 151 // become part of the block. If gen is nil, the blocks will be empty 152 // and their coinbase will be the zero address. 153 // 154 // Blocks created by GenerateChain do not contain valid proof of work 155 // values. Inserting them into BlockChain requires use of 156 // a similar non-validating proof of work implementation. 157 func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db qctdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) { 158 if config == nil { 159 config = params.TestChainConfig 160 } 161 blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n) 162 genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) { 163 // TODO(karalabe): This is needed for clique, which depends on multiple blocks. 164 // It's nonetheless ugly to spin up a blockchain here. Get rid of this somehow. 165 blockchain, _ := NewBlockChain(db, nil, config, engine, vm.Config{}) 166 defer blockchain.Stop() 167 168 b := &BlockGen{i: i, parent: parent, chain: blocks, chainReader: blockchain, statedb: statedb, config: config, engine: engine} 169 b.header = makeHeader(b.chainReader, parent, statedb, b.engine) 170 171 // Mutate the state and block according to any hard-fork specs 172 if daoBlock := config.DAOForkBlock; daoBlock != nil { 173 limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange) 174 if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 { 175 if config.DAOForkSupport { 176 b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra) 177 } 178 } 179 } 180 if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 { 181 misc.ApplyDAOHardFork(statedb) 182 } 183 // Execute any user modifications to the block and finalize it 184 if gen != nil { 185 gen(i, b) 186 } 187 188 if b.engine != nil { 189 //dpos.AccumulateRewards(config, statedb, h, b.uncles) 190 b.header.DposContext = parent.Header().DposContext 191 192 dposContext, err := types.NewDposContextFromProto(blockchain.db, parent.Header().DposContext) 193 if err != nil { 194 return nil, nil 195 } 196 block, _ := b.engine.Finalize(b.chainReader, b.header, statedb, b.txs, b.uncles, b.receipts, dposContext) 197 // Write state changes to db 198 root, err := statedb.Commit(config.IsEIP158(b.header.Number)) 199 if err != nil { 200 panic(fmt.Sprintf("state write error: %v", err)) 201 } 202 if err := statedb.Database().TrieDB().Commit(root, false); err != nil { 203 panic(fmt.Sprintf("trie write error: %v", err)) 204 } 205 return block, b.receipts 206 } 207 return nil, nil 208 } 209 for i := 0; i < n; i++ { 210 statedb, err := state.New(parent.Root(), state.NewDatabase(db)) 211 if err != nil { 212 panic(err) 213 } 214 block, receipt := genblock(i, parent, statedb) 215 blocks[i] = block 216 receipts[i] = receipt 217 parent = block 218 } 219 return blocks, receipts 220 } 221 222 func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header { 223 var time *big.Int 224 if parent.Time() == nil { 225 time = big.NewInt(10) 226 } else { 227 time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds 228 } 229 230 return &types.Header{ 231 Root: state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())), 232 ParentHash: parent.Hash(), 233 Coinbase: parent.Coinbase(), 234 Difficulty: engine.CalcDifficulty(chain, time.Uint64(), &types.Header{ 235 Number: parent.Number(), 236 Time: new(big.Int).Sub(time, big.NewInt(10)), 237 Difficulty: parent.Difficulty(), 238 UncleHash: parent.UncleHash(), 239 }), 240 DposContext: &types.DposContextProto{}, 241 GasLimit: CalcGasLimit(parent), 242 Number: new(big.Int).Add(parent.Number(), common.Big1), 243 Time: time, 244 } 245 } 246 247 // newCanonical creates a chain database, and injects a deterministic canonical 248 // chain. Depending on the full flag, if creates either a full block chain or a 249 // header only chain. 250 func newCanonical(engine consensus.Engine, n int, full bool) (qctdb.Database, *BlockChain, error) { 251 // Initialize a fresh chain with only a genesis block 252 gspec := new(Genesis) 253 db, _ := qctdb.NewMemDatabase() 254 genesis := gspec.MustCommit(db) 255 256 blockchain, _ := NewBlockChain(db, nil, params.AllDPOSProtocolChanges, engine, vm.Config{}) 257 // Create and inject the requested chain 258 if n == 0 { 259 return db, blockchain, nil 260 } 261 if full { 262 // Full block-chain requested 263 blocks := makeBlockChain(genesis, n, engine, db, canonicalSeed) 264 _, err := blockchain.InsertChain(blocks) 265 return db, blockchain, err 266 } 267 // Header-only chain requested 268 headers := makeHeaderChain(genesis.Header(), n, engine, db, canonicalSeed) 269 _, err := blockchain.InsertHeaderChain(headers, 1) 270 return db, blockchain, err 271 } 272 273 // makeHeaderChain creates a deterministic chain of headers rooted at parent. 274 func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db qctdb.Database, seed int) []*types.Header { 275 blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed) 276 headers := make([]*types.Header, len(blocks)) 277 for i, block := range blocks { 278 headers[i] = block.Header() 279 } 280 return headers 281 } 282 283 // makeBlockChain creates a deterministic chain of blocks rooted at parent. 284 func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db qctdb.Database, seed int) []*types.Block { 285 blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) { 286 b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)}) 287 }) 288 return blocks 289 }