OSDN Git Service

Coinbase arbitrary (#1219)
[bytom/bytom.git] / mining / mining.go
1 package mining
2
3 import (
4         "sort"
5         "strconv"
6         "time"
7
8         log "github.com/sirupsen/logrus"
9
10         "github.com/bytom/account"
11         "github.com/bytom/blockchain/txbuilder"
12         "github.com/bytom/consensus"
13         "github.com/bytom/errors"
14         "github.com/bytom/protocol"
15         "github.com/bytom/protocol/bc"
16         "github.com/bytom/protocol/bc/types"
17         "github.com/bytom/protocol/state"
18         "github.com/bytom/protocol/validation"
19         "github.com/bytom/protocol/vm/vmutil"
20 )
21
22 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
23 // based on the passed block height to the provided address.  When the address
24 // is nil, the coinbase transaction will instead be redeemable by anyone.
25 func createCoinbaseTx(accountManager *account.Manager, amount uint64, blockHeight uint64) (tx *types.Tx, err error) {
26         amount += consensus.BlockSubsidy(blockHeight)
27         arbitrary := append([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...)
28
29         var script []byte
30         if accountManager == nil {
31                 script, err = vmutil.DefaultCoinbaseProgram()
32         } else {
33                 script, err = accountManager.GetCoinbaseControlProgram()
34                 arbitrary = append(arbitrary, accountManager.GetCoinbaseArbitrary()...)
35         }
36         if err != nil {
37                 return nil, err
38         }
39
40         if len(arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
41                 return nil, validation.ErrCoinbaseArbitraryOversize
42         }
43
44         builder := txbuilder.NewBuilder(time.Now())
45         if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
46                 return nil, err
47         }
48         if err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {
49                 return nil, err
50         }
51         _, txData, err := builder.Build()
52         if err != nil {
53                 return nil, err
54         }
55
56         byteData, err := txData.MarshalText()
57         if err != nil {
58                 return nil, err
59         }
60         txData.SerializedSize = uint64(len(byteData))
61
62         tx = &types.Tx{
63                 TxData: *txData,
64                 Tx:     types.MapTx(txData),
65         }
66         return tx, nil
67 }
68
69 // NewBlockTemplate returns a new block template that is ready to be solved
70 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) (b *types.Block, err error) {
71         view := state.NewUtxoViewpoint()
72         txStatus := bc.NewTransactionStatus()
73         txStatus.SetStatus(0, false)
74         txEntries := []*bc.Tx{nil}
75         gasUsed := uint64(0)
76         txFee := uint64(0)
77
78         // get preblock info for generate next block
79         preBlockHeader := c.BestBlockHeader()
80         preBlockHash := preBlockHeader.Hash()
81         nextBlockHeight := preBlockHeader.Height + 1
82         nextBits, err := c.CalcNextBits(&preBlockHash)
83         if err != nil {
84                 return nil, err
85         }
86
87         b = &types.Block{
88                 BlockHeader: types.BlockHeader{
89                         Version:           1,
90                         Height:            nextBlockHeight,
91                         PreviousBlockHash: preBlockHash,
92                         Timestamp:         uint64(time.Now().Unix()),
93                         BlockCommitment:   types.BlockCommitment{},
94                         Bits:              nextBits,
95                 },
96         }
97         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
98         b.Transactions = []*types.Tx{nil}
99
100         txs := txPool.GetTransactions()
101         sort.Sort(byTime(txs))
102         for _, txDesc := range txs {
103                 tx := txDesc.Tx.Tx
104                 gasOnlyTx := false
105
106                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
107                         log.WithField("error", err).Error("mining block generate skip tx due to")
108                         txPool.RemoveTransaction(&tx.ID)
109                         continue
110                 }
111
112                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
113                 if err != nil {
114                         if !gasStatus.GasValid {
115                                 log.WithField("error", err).Error("mining block generate skip tx due to")
116                                 txPool.RemoveTransaction(&tx.ID)
117                                 continue
118                         }
119                         gasOnlyTx = true
120                 }
121
122                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
123                         break
124                 }
125
126                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
127                         log.WithField("error", err).Error("mining block generate skip tx due to")
128                         txPool.RemoveTransaction(&tx.ID)
129                         continue
130                 }
131
132                 txStatus.SetStatus(len(b.Transactions), gasOnlyTx)
133                 b.Transactions = append(b.Transactions, txDesc.Tx)
134                 txEntries = append(txEntries, tx)
135                 gasUsed += uint64(gasStatus.GasUsed)
136                 txFee += txDesc.Fee
137
138                 if gasUsed == consensus.MaxBlockGas {
139                         break
140                 }
141         }
142
143         // creater coinbase transaction
144         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
145         if err != nil {
146                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
147         }
148         txEntries[0] = b.Transactions[0].Tx
149
150         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.TxMerkleRoot(txEntries)
151         if err != nil {
152                 return nil, err
153         }
154
155         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = bc.TxStatusMerkleRoot(txStatus.VerifyStatus)
156         return b, err
157 }