OSDN Git Service

AnnotatedInput add AssetDifinition for issue (#1450)
[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         if err := txStatus.SetStatus(0, false); err != nil {
74                 return nil, err
75         }
76         txEntries := []*bc.Tx{nil}
77         gasUsed := uint64(0)
78         txFee := uint64(0)
79
80         // get preblock info for generate next block
81         preBlockHeader := c.BestBlockHeader()
82         preBlockHash := preBlockHeader.Hash()
83         nextBlockHeight := preBlockHeader.Height + 1
84         nextBits, err := c.CalcNextBits(&preBlockHash)
85         if err != nil {
86                 return nil, err
87         }
88
89         b = &types.Block{
90                 BlockHeader: types.BlockHeader{
91                         Version:           1,
92                         Height:            nextBlockHeight,
93                         PreviousBlockHash: preBlockHash,
94                         Timestamp:         uint64(time.Now().Unix()),
95                         BlockCommitment:   types.BlockCommitment{},
96                         Bits:              nextBits,
97                 },
98         }
99         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
100         b.Transactions = []*types.Tx{nil}
101
102         txs := txPool.GetTransactions()
103         sort.Sort(byTime(txs))
104         for _, txDesc := range txs {
105                 tx := txDesc.Tx.Tx
106                 gasOnlyTx := false
107
108                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
109                         blkGenSkipTxForErr(txPool, &tx.ID, err)
110                         continue
111                 }
112
113                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
114                 if err != nil {
115                         if !gasStatus.GasValid {
116                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
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                         blkGenSkipTxForErr(txPool, &tx.ID, err)
128                         continue
129                 }
130
131                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
132                         return nil, err
133                 }
134
135                 b.Transactions = append(b.Transactions, txDesc.Tx)
136                 txEntries = append(txEntries, tx)
137                 gasUsed += uint64(gasStatus.GasUsed)
138                 txFee += txDesc.Fee
139
140                 if gasUsed == consensus.MaxBlockGas {
141                         break
142                 }
143         }
144
145         // creater coinbase transaction
146         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
147         if err != nil {
148                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
149         }
150         txEntries[0] = b.Transactions[0].Tx
151
152         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
153         if err != nil {
154                 return nil, err
155         }
156
157         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
158         return b, err
159 }
160
161 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
162         log.WithField("error", err).Error("mining block generation: skip tx due to")
163         txPool.RemoveTransaction(txHash)
164 }