8 "github.com/vapor/common"
10 log "github.com/sirupsen/logrus"
12 "github.com/vapor/account"
13 "github.com/vapor/blockchain/txbuilder"
14 "github.com/vapor/config"
15 "github.com/vapor/consensus"
16 engine "github.com/vapor/consensus/consensus"
17 "github.com/vapor/crypto/ed25519/chainkd"
18 "github.com/vapor/errors"
19 "github.com/vapor/protocol"
20 "github.com/vapor/protocol/bc"
21 "github.com/vapor/protocol/bc/types"
22 "github.com/vapor/protocol/state"
23 "github.com/vapor/protocol/validation"
24 "github.com/vapor/protocol/vm/vmutil"
27 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
28 // based on the passed block height to the provided address. When the address
29 // is nil, the coinbase transaction will instead be redeemable by anyone.
30 func createCoinbaseTx(accountManager *account.Manager, amount uint64, blockHeight uint64) (tx *types.Tx, err error) {
31 //amount += consensus.BlockSubsidy(blockHeight)
32 arbitrary := append([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...)
35 address, _ := common.DecodeAddress(config.CommonConfig.Consensus.Dpos.Coinbase, &consensus.ActiveNetParams)
36 redeemContract := address.ScriptAddress()
37 script, _ = vmutil.P2WPKHProgram(redeemContract)
43 if len(arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
44 return nil, validation.ErrCoinbaseArbitraryOversize
47 builder := txbuilder.NewBuilder(time.Now())
48 if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
51 if err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {
54 _, txData, err := builder.Build()
59 byteData, err := txData.MarshalText()
63 txData.SerializedSize = uint64(len(byteData))
67 Tx: types.MapTx(txData),
72 // NewBlockTemplate returns a new block template that is ready to be solved
73 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager, engine engine.Engine) (b *types.Block, err error) {
74 view := state.NewUtxoViewpoint()
75 txStatus := bc.NewTransactionStatus()
76 if err := txStatus.SetStatus(0, false); err != nil {
79 txEntries := []*bc.Tx{nil}
83 // get preblock info for generate next block
84 preBlockHeader := c.BestBlockHeader()
85 preBlockHash := preBlockHeader.Hash()
86 nextBlockHeight := preBlockHeader.Height + 1
89 if config.CommonConfig.Consensus.Dpos.XPrv == "" {
90 return nil, errors.New("Signer is empty")
92 xPrv.UnmarshalText([]byte(config.CommonConfig.Consensus.Dpos.XPrv))
93 xpub, _ := xPrv.XPub().MarshalText()
95 header := types.BlockHeader{
97 Height: nextBlockHeight,
98 PreviousBlockHash: preBlockHash,
99 Timestamp: uint64(time.Now().Unix()),
100 BlockCommitment: types.BlockCommitment{},
104 if err := engine.Prepare(c, &header); err != nil {
105 log.Error("Failed to prepare header for mining", "err", err)
110 bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
111 b.Transactions = []*types.Tx{nil}
113 txs := txPool.GetTransactions()
114 sort.Sort(byTime(txs))
115 for _, txDesc := range txs {
119 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
120 blkGenSkipTxForErr(txPool, &tx.ID, err)
123 gasStatus, err := validation.ValidateTx(tx, bcBlock)
125 if !gasStatus.GasValid {
126 blkGenSkipTxForErr(txPool, &tx.ID, err)
132 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
136 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
137 blkGenSkipTxForErr(txPool, &tx.ID, err)
141 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
145 b.Transactions = append(b.Transactions, txDesc.Tx)
146 txEntries = append(txEntries, tx)
147 gasUsed += uint64(gasStatus.GasUsed)
149 if gasUsed == consensus.MaxBlockGas {
154 if err := engine.Finalize(c, &header, txEntries[1:]); err != nil {
158 b.BlockHeader = header
159 // creater coinbase transaction
160 b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
162 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
164 txEntries[0] = b.Transactions[0].Tx
166 b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
171 b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
175 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
176 log.WithField("error", err).Error("mining block generation: skip tx due to")
177 txPool.RemoveTransaction(txHash)