OSDN Git Service

594390455fa3dcfee3ae54e103f01fecd3e6d5cf
[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, engine engine.Engine) (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         var xPrv chainkd.XPrv
97         if config.CommonConfig.Consensus.Dpos.XPrv == "" {
98                 return nil, errors.New("Signer is empty")
99         }
100         xPrv.UnmarshalText([]byte(config.CommonConfig.Consensus.Dpos.XPrv))
101         xpub, _ := xPrv.XPub().MarshalText()
102
103         header := types.BlockHeader{
104                 Version:           1,
105                 Height:            nextBlockHeight,
106                 PreviousBlockHash: preBlockHash,
107                 Timestamp:         uint64(time.Now().Unix()),
108                 BlockCommitment:   types.BlockCommitment{},
109                 Coinbase:          xpub,
110                 //Extra:             make([]byte, 32+65),
111         }
112
113         if err := engine.Prepare(c, &header); err != nil {
114                 log.Error("Failed to prepare header for mining", "err", err)
115                 return nil, err
116         }
117
118         b = &types.Block{}
119         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
120         b.Transactions = []*types.Tx{nil}
121
122         txs := txPool.GetTransactions()
123         sort.Sort(byTime(txs))
124         for _, txDesc := range txs {
125                 tx := txDesc.Tx.Tx
126                 gasOnlyTx := false
127
128                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
129                         blkGenSkipTxForErr(txPool, &tx.ID, err)
130                         continue
131                 }
132                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
133                 if err != nil {
134                         if !gasStatus.GasValid {
135                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
136                                 continue
137                         }
138                         gasOnlyTx = true
139                 }
140
141                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
142                         break
143                 }
144
145                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
146                         blkGenSkipTxForErr(txPool, &tx.ID, err)
147                         continue
148                 }
149
150                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
151                         return nil, err
152                 }
153
154                 b.Transactions = append(b.Transactions, txDesc.Tx)
155                 txEntries = append(txEntries, tx)
156                 gasUsed += uint64(gasStatus.GasUsed)
157                 txFee += txDesc.Fee
158                 if gasUsed == consensus.MaxBlockGas {
159                         break
160                 }
161         }
162
163         if txFee == 0 {
164                 return nil, nil
165         }
166
167         if err := engine.Finalize(c, &header, txEntries[1:]); err != nil {
168                 return nil, err
169         }
170
171         b.BlockHeader = header
172         // creater coinbase transaction
173         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
174         if err != nil {
175                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
176         }
177         txEntries[0] = b.Transactions[0].Tx
178
179         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
180         if err != nil {
181                 return nil, err
182         }
183
184         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
185         return b, err
186 }
187
188 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
189         log.WithField("error", err).Error("mining block generation: skip tx due to")
190         txPool.RemoveTransaction(txHash)
191 }