OSDN Git Service

21862499399f4c894406418d803af3f396cb5abf
[bytom/vapor.git] / proposal / proposal.go
1 package proposal
2
3 import (
4         "sort"
5         "strconv"
6         "time"
7
8         log "github.com/sirupsen/logrus"
9
10         "github.com/bytom/vapor/account"
11         "github.com/bytom/vapor/blockchain/txbuilder"
12         "github.com/bytom/vapor/consensus"
13         "github.com/bytom/vapor/errors"
14         "github.com/bytom/vapor/protocol"
15         "github.com/bytom/vapor/protocol/bc"
16         "github.com/bytom/vapor/protocol/bc/types"
17         "github.com/bytom/vapor/protocol/state"
18         "github.com/bytom/vapor/protocol/validation"
19         "github.com/bytom/vapor/protocol/vm/vmutil"
20 )
21
22 const (
23         logModule     = "mining"
24         batchApplyNum = 64
25
26         timeoutOk = iota + 1
27         timeoutWarn
28         timeoutCritical
29 )
30
31 // NewBlockTemplate returns a new block template that is ready to be solved
32 func NewBlockTemplate(chain *protocol.Chain, accountManager *account.Manager, timestamp uint64, warnDuration, criticalDuration time.Duration) (*types.Block, error) {
33         builder := newBlockBuilder(chain, accountManager, timestamp, warnDuration, criticalDuration)
34         return builder.build()
35 }
36
37 type blockBuilder struct {
38         chain          *protocol.Chain
39         accountManager *account.Manager
40
41         block    *types.Block
42         txStatus *bc.TransactionStatus
43         utxoView *state.UtxoViewpoint
44
45         warnTimeoutCh     <-chan time.Time
46         criticalTimeoutCh <-chan time.Time
47         timeoutStatus     uint8
48         gasLeft           int64
49 }
50
51 func newBlockBuilder(chain *protocol.Chain, accountManager *account.Manager, timestamp uint64, warnDuration, criticalDuration time.Duration) *blockBuilder {
52         preBlockHeader := chain.BestBlockHeader()
53         block := &types.Block{
54                 BlockHeader: types.BlockHeader{
55                         Version:           1,
56                         Height:            preBlockHeader.Height + 1,
57                         PreviousBlockHash: preBlockHeader.Hash(),
58                         Timestamp:         timestamp,
59                         BlockCommitment:   types.BlockCommitment{},
60                         BlockWitness:      types.BlockWitness{Witness: make([][]byte, consensus.ActiveNetParams.NumOfConsensusNode)},
61                 },
62         }
63
64         builder := &blockBuilder{
65                 chain:             chain,
66                 accountManager:    accountManager,
67                 block:             block,
68                 txStatus:          bc.NewTransactionStatus(),
69                 utxoView:          state.NewUtxoViewpoint(),
70                 warnTimeoutCh:     time.After(warnDuration),
71                 criticalTimeoutCh: time.After(criticalDuration),
72                 gasLeft:           int64(consensus.ActiveNetParams.MaxBlockGas),
73                 timeoutStatus:     timeoutOk,
74         }
75         return builder
76 }
77
78 func (b *blockBuilder) applyCoinbaseTransaction() error {
79         coinbaseTx, err := b.createCoinbaseTx()
80         if err != nil {
81                 return errors.Wrap(err, "fail on create coinbase tx")
82         }
83
84         gasState, err := validation.ValidateTx(coinbaseTx.Tx, &bc.Block{BlockHeader: &bc.BlockHeader{Height: b.block.Height}, Transactions: []*bc.Tx{coinbaseTx.Tx}})
85         if err != nil {
86                 return err
87         }
88
89         b.block.Transactions = append(b.block.Transactions, coinbaseTx)
90         if err := b.txStatus.SetStatus(0, false); err != nil {
91                 return err
92         }
93
94         b.gasLeft -= gasState.GasUsed
95         return nil
96 }
97
98 func (b *blockBuilder) applyTransactions(txs []*types.Tx, timeoutStatus uint8) error {
99         tempTxs := []*types.Tx{}
100         for i := 0; i < len(txs); i++ {
101                 if tempTxs = append(tempTxs, txs[i]); len(tempTxs) < batchApplyNum && i != len(txs)-1 {
102                         continue
103                 }
104
105                 results, gasLeft := b.preValidateTxs(tempTxs, b.chain, b.utxoView, b.gasLeft)
106                 for _, result := range results {
107                         if result.err != nil && !result.gasOnly {
108                                 log.WithFields(log.Fields{"module": logModule, "error": result.err}).Error("mining block generation: skip tx due to")
109                                 b.chain.GetTxPool().RemoveTransaction(&result.tx.ID)
110                                 continue
111                         }
112
113                         if err := b.txStatus.SetStatus(len(b.block.Transactions), result.gasOnly); err != nil {
114                                 return err
115                         }
116
117                         b.block.Transactions = append(b.block.Transactions, result.tx)
118                 }
119
120                 b.gasLeft = gasLeft
121                 tempTxs = []*types.Tx{}
122                 if b.getTimeoutStatus() >= timeoutStatus {
123                         break
124                 }
125         }
126         return nil
127 }
128
129 func (b *blockBuilder) applyTransactionFromPool() error {
130         txDescList := b.chain.GetTxPool().GetTransactions()
131         sort.Sort(byTime(txDescList))
132
133         poolTxs := make([]*types.Tx, len(txDescList))
134         for i, txDesc := range txDescList {
135                 poolTxs[i] = txDesc.Tx
136         }
137
138         return b.applyTransactions(poolTxs, timeoutWarn)
139 }
140
141 func (b *blockBuilder) applyTransactionFromSubProtocol() error {
142         isTimeout := func() bool {
143                 return b.getTimeoutStatus() > timeoutOk
144         }
145
146         for i, p := range b.chain.SubProtocols() {
147                 if b.gasLeft <= 0 || isTimeout() {
148                         break
149                 }
150
151                 subTxs, err := p.BeforeProposalBlock(b.block.Transactions, b.block.Height, b.gasLeft, isTimeout)
152                 if err != nil {
153                         log.WithFields(log.Fields{"module": logModule, "index": i, "error": err}).Error("failed on sub protocol txs package")
154                         continue
155                 }
156
157                 if err := b.applyTransactions(subTxs, timeoutCritical); err != nil {
158                         return err
159                 }
160         }
161         return nil
162 }
163
164 func (b *blockBuilder) build() (*types.Block, error) {
165         if err := b.applyCoinbaseTransaction(); err != nil {
166                 return nil, err
167         }
168
169         if err := b.applyTransactionFromPool(); err != nil {
170                 return nil, err
171         }
172
173         if err := b.applyTransactionFromSubProtocol(); err != nil {
174                 return nil, err
175         }
176
177         if err := b.calcBlockCommitment(); err != nil {
178                 return nil, err
179         }
180
181         if err := b.chain.SignBlockHeader(&b.block.BlockHeader); err != nil {
182                 return nil, err
183         }
184
185         return b.block, nil
186 }
187
188 func (b *blockBuilder) calcBlockCommitment() (err error) {
189         var txEntries []*bc.Tx
190         for _, tx := range b.block.Transactions {
191                 txEntries = append(txEntries, tx.Tx)
192         }
193
194         b.block.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
195         if err != nil {
196                 return err
197         }
198
199         b.block.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(b.txStatus.VerifyStatus)
200         return err
201 }
202
203 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
204 // based on the passed block height to the provided address.  When the address
205 // is nil, the coinbase transaction will instead be redeemable by anyone.
206 func (b *blockBuilder) createCoinbaseTx() (*types.Tx, error) {
207         consensusResult, err := b.chain.GetConsensusResultByHash(&b.block.PreviousBlockHash)
208         if err != nil {
209                 return nil, err
210         }
211
212         rewards, err := consensusResult.GetCoinbaseRewards(b.block.Height - 1)
213         if err != nil {
214                 return nil, err
215         }
216
217         return createCoinbaseTxByReward(b.accountManager, b.block.Height, rewards)
218 }
219
220 func (b *blockBuilder) getTimeoutStatus() uint8 {
221         if b.timeoutStatus == timeoutCritical {
222                 return b.timeoutStatus
223         }
224
225         select {
226         case <-b.criticalTimeoutCh:
227                 b.timeoutStatus = timeoutCritical
228         case <-b.warnTimeoutCh:
229                 b.timeoutStatus = timeoutWarn
230         default:
231         }
232
233         return b.timeoutStatus
234 }
235
236 func createCoinbaseTxByReward(accountManager *account.Manager, blockHeight uint64, rewards []state.CoinbaseReward) (tx *types.Tx, err error) {
237         arbitrary := append([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...)
238         var script []byte
239         if accountManager == nil {
240                 script, err = vmutil.DefaultCoinbaseProgram()
241         } else {
242                 script, err = accountManager.GetCoinbaseControlProgram()
243                 arbitrary = append(arbitrary, accountManager.GetCoinbaseArbitrary()...)
244         }
245         if err != nil {
246                 return nil, err
247         }
248
249         if len(arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
250                 return nil, validation.ErrCoinbaseArbitraryOversize
251         }
252
253         builder := txbuilder.NewBuilder(time.Now())
254         if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
255                 return nil, err
256         }
257
258         if err = builder.AddOutput(types.NewIntraChainOutput(*consensus.BTMAssetID, 0, script)); err != nil {
259                 return nil, err
260         }
261
262         for _, r := range rewards {
263                 if err = builder.AddOutput(types.NewIntraChainOutput(*consensus.BTMAssetID, r.Amount, r.ControlProgram)); err != nil {
264                         return nil, err
265                 }
266         }
267
268         _, txData, err := builder.Build()
269         if err != nil {
270                 return nil, err
271         }
272
273         byteData, err := txData.MarshalText()
274         if err != nil {
275                 return nil, err
276         }
277
278         txData.SerializedSize = uint64(len(byteData))
279         tx = &types.Tx{
280                 TxData: *txData,
281                 Tx:     types.MapTx(txData),
282         }
283         return tx, nil
284 }
285
286 type validateTxResult struct {
287         tx      *types.Tx
288         gasOnly bool
289         err     error
290 }
291
292 func (b *blockBuilder) preValidateTxs(txs []*types.Tx, chain *protocol.Chain, view *state.UtxoViewpoint, gasLeft int64) ([]*validateTxResult, int64) {
293         var results []*validateTxResult
294         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: chain.BestBlockHeight() + 1}}
295         bcTxs := make([]*bc.Tx, len(txs))
296         for i, tx := range txs {
297                 bcTxs[i] = tx.Tx
298         }
299
300         validateResults := validation.ValidateTxs(bcTxs, bcBlock)
301         for i := 0; i < len(validateResults) && gasLeft > 0; i++ {
302                 gasOnlyTx := false
303                 gasStatus := validateResults[i].GetGasState()
304                 if err := validateResults[i].GetError(); err != nil {
305                         if !gasStatus.GasValid {
306                                 results = append(results, &validateTxResult{tx: txs[i], err: err})
307                                 continue
308                         }
309                         gasOnlyTx = true
310                 }
311
312                 if err := chain.GetTransactionsUtxo(view, []*bc.Tx{bcTxs[i]}); err != nil {
313                         results = append(results, &validateTxResult{tx: txs[i], err: err})
314                         continue
315                 }
316
317                 if gasLeft-gasStatus.GasUsed < 0 {
318                         break
319                 }
320
321                 if err := view.ApplyTransaction(bcBlock, bcTxs[i], gasOnlyTx); err != nil {
322                         results = append(results, &validateTxResult{tx: txs[i], err: err})
323                         continue
324                 }
325
326                 if err := b.validateBySubProtocols(txs[i], validateResults[i].GetError() != nil, chain.SubProtocols()); err != nil {
327                         results = append(results, &validateTxResult{tx: txs[i], err: err})
328                         continue
329                 }
330
331                 results = append(results, &validateTxResult{tx: txs[i], gasOnly: gasOnlyTx, err: validateResults[i].GetError()})
332                 gasLeft -= gasStatus.GasUsed
333         }
334         return results, gasLeft
335 }
336
337 func (b *blockBuilder) validateBySubProtocols(tx *types.Tx, statusFail bool, subProtocols []protocol.SubProtocol) error {
338         for _, subProtocol := range subProtocols {
339                 verifyResult := &bc.TxVerifyResult{StatusFail: statusFail}
340                 if err := subProtocol.ValidateTx(tx, verifyResult, b.block.Height); err != nil {
341                         return err
342                 }
343         }
344         return nil
345 }