10 "github.com/vapor/common"
12 log "github.com/sirupsen/logrus"
14 "github.com/vapor/account"
15 "github.com/vapor/blockchain/txbuilder"
16 "github.com/vapor/config"
17 "github.com/vapor/consensus"
18 engine "github.com/vapor/consensus/consensus"
19 "github.com/vapor/crypto/ed25519/chainkd"
20 "github.com/vapor/errors"
21 "github.com/vapor/protocol"
22 "github.com/vapor/protocol/bc"
23 "github.com/vapor/protocol/bc/types"
24 "github.com/vapor/protocol/state"
25 "github.com/vapor/protocol/validation"
26 "github.com/vapor/protocol/vm/vmutil"
29 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
30 // based on the passed block height to the provided address. When the address
31 // is nil, the coinbase transaction will instead be redeemable by anyone.
32 func createCoinbaseTx(accountManager *account.Manager, amount uint64, blockHeight uint64, delegateInfo engine.DelegateInfo, timestamp uint64) (tx *types.Tx, err error) {
33 //amount += consensus.BlockSubsidy(blockHeight)
34 arbitrary := append([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...)
37 address, _ := common.DecodeAddress(config.CommonConfig.Consensus.Dpos.Coinbase, &consensus.ActiveNetParams)
38 redeemContract := address.ScriptAddress()
39 script, _ = vmutil.P2WPKHProgram(redeemContract)
45 if len(arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
46 return nil, validation.ErrCoinbaseArbitraryOversize
49 builder := txbuilder.NewBuilder(time.Now())
50 if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
54 if err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {
57 _, txData, err := builder.Build()
62 byteData, err := txData.MarshalText()
66 txData.SerializedSize = uint64(len(byteData))
68 delegates := engine.DelegateInfoList{}
69 delegates.Delegate = delegateInfo
72 if config.CommonConfig.Consensus.Dpos.XPrv == "" {
73 return nil, errors.New("Signer is empty")
75 xPrv.UnmarshalText([]byte(config.CommonConfig.Consensus.Dpos.XPrv))
78 binary.LittleEndian.PutUint64(buf[:], timestamp)
79 delegates.SigTime = xPrv.Sign(buf)
80 delegates.Xpub = xPrv.XPub()
82 data, err := json.Marshal(&delegates)
87 txData.ReferenceData = data
91 Tx: types.MapTx(txData),
96 // NewBlockTemplate returns a new block template that is ready to be solved
97 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager, engine engine.Engine, delegateInfo engine.DelegateInfo) (b *types.Block, err error) {
98 view := state.NewUtxoViewpoint()
99 txStatus := bc.NewTransactionStatus()
100 if err := txStatus.SetStatus(0, false); err != nil {
103 txEntries := []*bc.Tx{nil}
107 // get preblock info for generate next block
108 preBlockHeader := c.BestBlockHeader()
109 preBlockHash := preBlockHeader.Hash()
110 nextBlockHeight := preBlockHeader.Height + 1
112 var xPrv chainkd.XPrv
113 if config.CommonConfig.Consensus.Dpos.XPrv == "" {
114 return nil, errors.New("Signer is empty")
116 xPrv.UnmarshalText([]byte(config.CommonConfig.Consensus.Dpos.XPrv))
117 xpub, _ := xPrv.XPub().MarshalText()
119 header := types.BlockHeader{
121 Height: nextBlockHeight,
122 PreviousBlockHash: preBlockHash,
123 Timestamp: uint64(time.Now().Unix()),
124 BlockCommitment: types.BlockCommitment{},
128 if err := engine.Prepare(c, &header); err != nil {
129 log.Error("Failed to prepare header for mining", "err", err)
134 bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
135 b.Transactions = []*types.Tx{nil}
137 txs := txPool.GetTransactions()
138 sort.Sort(byTime(txs))
139 for _, txDesc := range txs {
143 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
144 blkGenSkipTxForErr(txPool, &tx.ID, err)
147 gasStatus, err := validation.ValidateTx(tx, bcBlock)
149 if !gasStatus.GasValid {
150 blkGenSkipTxForErr(txPool, &tx.ID, err)
156 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
160 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
161 blkGenSkipTxForErr(txPool, &tx.ID, err)
165 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
169 b.Transactions = append(b.Transactions, txDesc.Tx)
170 txEntries = append(txEntries, tx)
171 gasUsed += uint64(gasStatus.GasUsed)
173 if gasUsed == consensus.MaxBlockGas {
178 if err := engine.Finalize(c, &header, txEntries[1:]); err != nil {
182 b.BlockHeader = header
183 // creater coinbase transaction
184 b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight, delegateInfo, bcBlock.Timestamp)
186 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
188 txEntries[0] = b.Transactions[0].Tx
190 b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
195 b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
199 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
200 log.WithField("error", err).Error("mining block generation: skip tx due to")
201 txPool.RemoveTransaction(txHash)