OSDN Git Service

e2dfcac56b6e56000d0e8e586375538bbe381258
[bytom/vapor.git] / mining / mining.go
1 package mining
2
3 import (
4         "sort"
5         "strconv"
6         "time"
7
8         "github.com/vapor/common"
9
10         log "github.com/sirupsen/logrus"
11
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"
25 )
26
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))...)
33
34         var script []byte
35         address, _ := common.DecodeAddress(config.CommonConfig.Consensus.Dpos.Coinbase, &consensus.ActiveNetParams)
36         redeemContract := address.ScriptAddress()
37         script, _ = vmutil.P2WPKHProgram(redeemContract)
38         /*
39                 if accountManager == nil {
40                         script, err = vmutil.DefaultCoinbaseProgram()
41                 } else {
42
43                         script, err = accountManager.GetCoinbaseControlProgram()
44                         arbitrary = append(arbitrary, accountManager.GetCoinbaseArbitrary()...)
45                 }
46         */
47         if err != nil {
48                 return nil, err
49         }
50
51         if len(arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
52                 return nil, validation.ErrCoinbaseArbitraryOversize
53         }
54
55         builder := txbuilder.NewBuilder(time.Now())
56         if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
57                 return nil, err
58         }
59         if err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {
60                 return nil, err
61         }
62         _, txData, err := builder.Build()
63         if err != nil {
64                 return nil, err
65         }
66
67         byteData, err := txData.MarshalText()
68         if err != nil {
69                 return nil, err
70         }
71         txData.SerializedSize = uint64(len(byteData))
72
73         tx = &types.Tx{
74                 TxData: *txData,
75                 Tx:     types.MapTx(txData),
76         }
77         return tx, nil
78 }
79
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 {
85                 return nil, err
86         }
87         txEntries := []*bc.Tx{nil}
88         gasUsed := uint64(0)
89         txFee := uint64(0)
90
91         // get preblock info for generate next block
92         preBlockHeader := c.BestBlockHeader()
93         preBlockHash := preBlockHeader.Hash()
94         nextBlockHeight := preBlockHeader.Height + 1
95
96         header := types.BlockHeader{
97                 Version:           1,
98                 Height:            nextBlockHeight,
99                 PreviousBlockHash: preBlockHash,
100                 Timestamp:         uint64(time.Now().Unix()),
101                 BlockCommitment:   types.BlockCommitment{},
102         }
103
104         b = &types.Block{BlockHeader: header}
105         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
106         b.Transactions = []*types.Tx{nil}
107
108         txs := txPool.GetTransactions()
109         sort.Sort(byTime(txs))
110         for _, txDesc := range txs {
111                 tx := txDesc.Tx.Tx
112                 gasOnlyTx := false
113
114                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
115                         blkGenSkipTxForErr(txPool, &tx.ID, err)
116                         continue
117                 }
118
119                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
120                 if err != nil {
121                         if !gasStatus.GasValid {
122                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
123                                 continue
124                         }
125                         gasOnlyTx = true
126                 }
127
128                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
129                         break
130                 }
131
132                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
133                         blkGenSkipTxForErr(txPool, &tx.ID, err)
134                         continue
135                 }
136
137                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
138                         return nil, err
139                 }
140
141                 b.Transactions = append(b.Transactions, txDesc.Tx)
142                 txEntries = append(txEntries, tx)
143                 gasUsed += uint64(gasStatus.GasUsed)
144                 txFee += txDesc.Fee
145
146                 if gasUsed == consensus.MaxBlockGas {
147                         break
148                 }
149         }
150         if txFee == 0 {
151                 return nil, err
152         }
153
154         // creater coinbase transaction
155         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
156         if err != nil {
157                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
158         }
159         txEntries[0] = b.Transactions[0].Tx
160
161         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
162         if err != nil {
163                 return nil, err
164         }
165
166         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
167         return b, err
168 }
169
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 {
175                 return nil, err
176         }
177         txEntries := []*bc.Tx{nil}
178         gasUsed := uint64(0)
179         txFee := uint64(0)
180
181         // get preblock info for generate next block
182         preBlockHeader := c.BestBlockHeader()
183         preBlockHash := preBlockHeader.Hash()
184         nextBlockHeight := preBlockHeader.Height + 1
185
186         var xPrv chainkd.XPrv
187         if config.CommonConfig.Consensus.Dpos.XPrv == "" {
188                 return nil, errors.New("Signer is empty")
189         }
190         xPrv.UnmarshalText([]byte(config.CommonConfig.Consensus.Dpos.XPrv))
191         xpub, _ := xPrv.XPub().MarshalText()
192
193         header := types.BlockHeader{
194                 Version:           1,
195                 Height:            nextBlockHeight,
196                 PreviousBlockHash: preBlockHash,
197                 Timestamp:         uint64(time.Now().Unix()),
198                 BlockCommitment:   types.BlockCommitment{},
199                 Coinbase:          xpub,
200                 //Extra:             make([]byte, 32+65),
201         }
202
203         if err := engine.Prepare(c, &header); err != nil {
204                 log.Error("Failed to prepare header for mining", "err", err)
205                 return nil, err
206         }
207
208         b = &types.Block{}
209         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
210         b.Transactions = []*types.Tx{nil}
211
212         txs := txPool.GetTransactions()
213         sort.Sort(byTime(txs))
214         for _, txDesc := range txs {
215                 tx := txDesc.Tx.Tx
216                 gasOnlyTx := false
217
218                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
219                         blkGenSkipTxForErr(txPool, &tx.ID, err)
220                         continue
221                 }
222                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
223                 if err != nil {
224                         if !gasStatus.GasValid {
225                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
226                                 continue
227                         }
228                         gasOnlyTx = true
229                 }
230
231                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
232                         break
233                 }
234
235                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
236                         blkGenSkipTxForErr(txPool, &tx.ID, err)
237                         continue
238                 }
239
240                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
241                         return nil, err
242                 }
243
244                 b.Transactions = append(b.Transactions, txDesc.Tx)
245                 txEntries = append(txEntries, tx)
246                 gasUsed += uint64(gasStatus.GasUsed)
247                 txFee += txDesc.Fee
248                 if gasUsed == consensus.MaxBlockGas {
249                         break
250                 }
251         }
252
253         if txFee == 0 {
254                 return nil, nil
255         }
256
257         if err := engine.Finalize(c, &header, txEntries[1:]); err != nil {
258                 return nil, err
259         }
260
261         b.BlockHeader = header
262         // creater coinbase transaction
263         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
264         if err != nil {
265                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
266         }
267         txEntries[0] = b.Transactions[0].Tx
268
269         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
270         if err != nil {
271                 return nil, err
272         }
273
274         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
275         return b, err
276 }
277
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)
281 }