4 "github.com/vapor/protocol"
5 "github.com/vapor/protocol/bc"
6 "github.com/vapor/protocol/bc/types"
7 "github.com/vapor/protocol/validation"
8 "github.com/vapor/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) {
15 txEntries := []*bc.Tx{nil}
16 txStatus := bc.NewTransactionStatus()
17 if err := txStatus.SetStatus(0, false); err != nil {
21 preBlockHeader := chain.BestBlockHeader()
23 BlockHeader: types.BlockHeader{
25 Height: preBlockHeader.Height + 1,
26 PreviousBlockHash: preBlockHeader.Hash(),
27 Timestamp: preBlockHeader.Timestamp + 1,
28 BlockCommitment: types.BlockCommitment{},
30 Transactions: []*types.Tx{nil},
33 bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: preBlockHeader.Height + 1}}
34 for _, tx := range txs {
36 gasStatus, err := validation.ValidateTx(tx.Tx, bcBlock)
38 if !gasStatus.GasValid {
44 txStatus.SetStatus(len(b.Transactions), gasOnlyTx)
45 b.Transactions = append(b.Transactions, tx)
46 txEntries = append(txEntries, tx.Tx)
47 gasUsed += uint64(gasStatus.GasUsed)
51 coinbaseTx, err := CreateCoinbaseTx(controlProgram, preBlockHeader.Height+1, txsFee)
56 b.Transactions[0] = coinbaseTx
57 txEntries[0] = coinbaseTx.Tx
58 b.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
63 b.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
67 // ReplaceCoinbase replace the coinbase tx of block with coinbaseTx
68 func ReplaceCoinbase(block *types.Block, coinbaseTx *types.Tx) (err error) {
69 block.Transactions[0] = coinbaseTx
70 txEntires := []*bc.Tx{coinbaseTx.Tx}
71 for i := 1; i < len(block.Transactions); i++ {
72 txEntires = append(txEntires, block.Transactions[i].Tx)
75 block.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntires)
79 // AppendBlocks append empty blocks to chain, mainly used to mature the coinbase tx
80 func AppendBlocks(chain *protocol.Chain, num uint64) error {
81 for i := uint64(0); i < num; i++ {
82 block, err := NewBlock(chain, nil, []byte{byte(vm.OP_TRUE)})
86 if _, err := chain.ProcessBlock(block); err != nil {