OSDN Git Service

e816bc463dd7cd250c4b6a955b12bbe82b54cbab
[bytom/vapor.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/vapor/account"
11         "github.com/vapor/blockchain/txbuilder"
12         "github.com/vapor/consensus"
13         "github.com/vapor/errors"
14         "github.com/vapor/protocol"
15         "github.com/vapor/protocol/bc"
16         "github.com/vapor/protocol/bc/types"
17         "github.com/vapor/protocol/state"
18         "github.com/vapor/protocol/validation"
19         "github.com/vapor/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
85         b = &types.Block{
86                 BlockHeader: types.BlockHeader{
87                         Version:           1,
88                         Height:            nextBlockHeight,
89                         PreviousBlockHash: preBlockHash,
90                         Timestamp:         uint64(time.Now().Unix()),
91                         BlockCommitment:   types.BlockCommitment{},
92                 },
93         }
94         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
95         b.Transactions = []*types.Tx{nil}
96
97         txs := txPool.GetTransactions()
98         sort.Sort(byTime(txs))
99         for _, txDesc := range txs {
100                 tx := txDesc.Tx.Tx
101                 gasOnlyTx := false
102
103                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
104                         blkGenSkipTxForErr(txPool, &tx.ID, err)
105                         continue
106                 }
107
108                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
109                 if err != nil {
110                         if !gasStatus.GasValid {
111                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
112                                 continue
113                         }
114                         gasOnlyTx = true
115                 }
116
117                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
118                         break
119                 }
120
121                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
122                         blkGenSkipTxForErr(txPool, &tx.ID, err)
123                         continue
124                 }
125
126                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
127                         return nil, err
128                 }
129
130                 b.Transactions = append(b.Transactions, txDesc.Tx)
131                 txEntries = append(txEntries, tx)
132                 gasUsed += uint64(gasStatus.GasUsed)
133                 txFee += txDesc.Fee
134
135                 if gasUsed == consensus.MaxBlockGas {
136                         break
137                 }
138         }
139         if txFee == 0 {
140                 return nil, err
141         }
142         // creater coinbase transaction
143         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
144         if err != nil {
145                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
146         }
147         txEntries[0] = b.Transactions[0].Tx
148
149         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
150         if err != nil {
151                 return nil, err
152         }
153
154         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
155         return b, err
156 }
157
158 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
159         log.WithField("error", err).Error("mining block generation: skip tx due to")
160         txPool.RemoveTransaction(txHash)
161 }