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)
39 if accountManager == nil {
40 script, err = vmutil.DefaultCoinbaseProgram()
43 script, err = accountManager.GetCoinbaseControlProgram()
44 arbitrary = append(arbitrary, accountManager.GetCoinbaseArbitrary()...)
51 if len(arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
52 return nil, validation.ErrCoinbaseArbitraryOversize
55 builder := txbuilder.NewBuilder(time.Now())
56 if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
59 if err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {
62 _, txData, err := builder.Build()
67 byteData, err := txData.MarshalText()
71 txData.SerializedSize = uint64(len(byteData))
75 Tx: types.MapTx(txData),
80 // NewBlockTemplate returns a new block template that is ready to be solved
81 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) (b *types.Block, err error) {
82 view := state.NewUtxoViewpoint()
83 txStatus := bc.NewTransactionStatus()
84 if err := txStatus.SetStatus(0, false); err != nil {
87 txEntries := []*bc.Tx{nil}
91 // get preblock info for generate next block
92 preBlockHeader := c.BestBlockHeader()
93 preBlockHash := preBlockHeader.Hash()
94 nextBlockHeight := preBlockHeader.Height + 1
96 header := types.BlockHeader{
98 Height: nextBlockHeight,
99 PreviousBlockHash: preBlockHash,
100 Timestamp: uint64(time.Now().Unix()),
101 BlockCommitment: types.BlockCommitment{},
104 b = &types.Block{BlockHeader: header}
105 bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
106 b.Transactions = []*types.Tx{nil}
108 txs := txPool.GetTransactions()
109 sort.Sort(byTime(txs))
110 for _, txDesc := range txs {
114 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
115 blkGenSkipTxForErr(txPool, &tx.ID, err)
119 gasStatus, err := validation.ValidateTx(tx, bcBlock)
121 if !gasStatus.GasValid {
122 blkGenSkipTxForErr(txPool, &tx.ID, err)
128 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
132 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
133 blkGenSkipTxForErr(txPool, &tx.ID, err)
137 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
141 b.Transactions = append(b.Transactions, txDesc.Tx)
142 txEntries = append(txEntries, tx)
143 gasUsed += uint64(gasStatus.GasUsed)
146 if gasUsed == consensus.MaxBlockGas {
154 // creater coinbase transaction
155 b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
157 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
159 txEntries[0] = b.Transactions[0].Tx
161 b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
166 b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
170 // NewBlockTemplate returns a new block template that is ready to be solved
171 func NewBlockTemplate1(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager, engine engine.Engine) (b *types.Block, err error) {
172 view := state.NewUtxoViewpoint()
173 txStatus := bc.NewTransactionStatus()
174 if err := txStatus.SetStatus(0, false); err != nil {
177 txEntries := []*bc.Tx{nil}
181 // get preblock info for generate next block
182 preBlockHeader := c.BestBlockHeader()
183 preBlockHash := preBlockHeader.Hash()
184 nextBlockHeight := preBlockHeader.Height + 1
186 var xPrv chainkd.XPrv
187 if config.CommonConfig.Consensus.Dpos.XPrv == "" {
188 return nil, errors.New("Signer is empty")
190 xPrv.UnmarshalText([]byte(config.CommonConfig.Consensus.Dpos.XPrv))
191 xpub, _ := xPrv.XPub().MarshalText()
193 header := types.BlockHeader{
195 Height: nextBlockHeight,
196 PreviousBlockHash: preBlockHash,
197 Timestamp: uint64(time.Now().Unix()),
198 BlockCommitment: types.BlockCommitment{},
200 //Extra: make([]byte, 32+65),
203 if err := engine.Prepare(c, &header); err != nil {
204 log.Error("Failed to prepare header for mining", "err", err)
209 bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
210 b.Transactions = []*types.Tx{nil}
212 txs := txPool.GetTransactions()
213 sort.Sort(byTime(txs))
214 for _, txDesc := range txs {
218 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
219 blkGenSkipTxForErr(txPool, &tx.ID, err)
222 gasStatus, err := validation.ValidateTx(tx, bcBlock)
224 if !gasStatus.GasValid {
225 blkGenSkipTxForErr(txPool, &tx.ID, err)
231 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
235 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
236 blkGenSkipTxForErr(txPool, &tx.ID, err)
240 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
244 b.Transactions = append(b.Transactions, txDesc.Tx)
245 txEntries = append(txEntries, tx)
246 gasUsed += uint64(gasStatus.GasUsed)
248 if gasUsed == consensus.MaxBlockGas {
257 if err := engine.Finalize(c, &header, txEntries[1:]); err != nil {
261 b.BlockHeader = header
262 // creater coinbase transaction
263 b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
265 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
267 txEntries[0] = b.Transactions[0].Tx
269 b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
274 b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
278 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
279 log.WithField("error", err).Error("mining block generation: skip tx due to")
280 txPool.RemoveTransaction(txHash)