4 "github.com/bytom/bytom/protocol"
5 "github.com/bytom/bytom/protocol/bc"
6 "github.com/bytom/bytom/protocol/bc/types"
7 "github.com/bytom/bytom/protocol/validation"
8 "github.com/bytom/bytom/protocol/vm"
11 // NewBlock create block according to the current status of chain
12 func NewBlock(chain *protocol.Chain, txs []*types.Tx, controlProgram []byte) (*types.Block, error) {
16 preBlockHeader := chain.BestBlockHeader()
19 BlockHeader: types.BlockHeader{
21 Height: preBlockHeader.Height + 1,
22 PreviousBlockHash: preBlockHeader.Hash(),
23 Timestamp: preBlockHeader.Timestamp + 10000,
24 BlockCommitment: types.BlockCommitment{},
26 Transactions: []*types.Tx{nil},
29 bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: preBlockHeader.Height + 1}}
30 for _, tx := range txs {
31 gasStatus, err := validation.ValidateTx(tx.Tx, bcBlock, chain.ProgramConverter)
36 b.Transactions = append(b.Transactions, tx)
37 gasUsed += uint64(gasStatus.GasUsed)
41 coinbaseTx, err := CreateCoinbaseTx(controlProgram, preBlockHeader.Height+1, txsFee)
46 b.Transactions[0] = coinbaseTx
48 b.Transactions = append(b.Transactions, txs...)
51 txEntries := []*bc.Tx{nil}
52 txEntries[0] = coinbaseTx.Tx
53 for _, tx := range txs {
54 txEntries = append(txEntries, tx.Tx)
56 b.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
60 // ReplaceCoinbase replace the coinbase tx of block with coinbaseTx
61 func ReplaceCoinbase(block *types.Block, coinbaseTx *types.Tx) (err error) {
62 block.Transactions[0] = coinbaseTx
63 txEntires := []*bc.Tx{coinbaseTx.Tx}
64 for i := 1; i < len(block.Transactions); i++ {
65 txEntires = append(txEntires, block.Transactions[i].Tx)
68 block.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntires)
72 // AppendBlocks append empty blocks to chain, mainly used to mature the coinbase tx
73 func AppendBlocks(chain *protocol.Chain, num uint64) error {
74 for i := uint64(0); i < num; i++ {
75 block, err := NewBlock(chain, nil, []byte{byte(vm.OP_TRUE)})
79 if _, err := chain.ProcessBlock(block); err != nil {