OSDN Git Service

Rollback pr3 (#496)
[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 := 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         cp, err := b.accountManager.GetCoinbaseControlProgram()
143         if err != nil {
144                 return err
145         }
146
147         isTimeout := func() bool {
148                 return b.getTimeoutStatus() > timeoutOk
149         }
150
151         for i, p := range b.chain.SubProtocols() {
152                 if b.gasLeft <= 0 || isTimeout() {
153                         break
154                 }
155
156                 subTxs, err := p.BeforeProposalBlock(b.block.Transactions, cp, b.block.Height, b.gasLeft, isTimeout)
157                 if err != nil {
158                         log.WithFields(log.Fields{"module": logModule, "index": i, "error": err}).Error("failed on sub protocol txs package")
159                         continue
160                 }
161
162                 if err := b.applyTransactions(subTxs, timeoutCritical); err != nil {
163                         return err
164                 }
165         }
166         return nil
167 }
168
169 func (b *blockBuilder) build() (*types.Block, error) {
170         if err := b.applyCoinbaseTransaction(); err != nil {
171                 return nil, err
172         }
173
174         if err := b.applyTransactionFromPool(); err != nil {
175                 return nil, err
176         }
177
178         if err := b.applyTransactionFromSubProtocol(); err != nil {
179                 return nil, err
180         }
181
182         if err := b.calcBlockCommitment(); err != nil {
183                 return nil, err
184         }
185
186         if err := b.chain.SignBlockHeader(&b.block.BlockHeader); err != nil {
187                 return nil, err
188         }
189
190         return b.block, nil
191 }
192
193 func (b *blockBuilder) calcBlockCommitment() (err error) {
194         var txEntries []*bc.Tx
195         for _, tx := range b.block.Transactions {
196                 txEntries = append(txEntries, tx.Tx)
197         }
198
199         b.block.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
200         if err != nil {
201                 return err
202         }
203
204         b.block.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(b.txStatus.VerifyStatus)
205         return err
206 }
207
208 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
209 // based on the passed block height to the provided address.  When the address
210 // is nil, the coinbase transaction will instead be redeemable by anyone.
211 func (b *blockBuilder) createCoinbaseTx() (*types.Tx, error) {
212         consensusResult, err := b.chain.GetConsensusResultByHash(&b.block.PreviousBlockHash)
213         if err != nil {
214                 return nil, err
215         }
216
217         rewards, err := consensusResult.GetCoinbaseRewards(b.block.Height - 1)
218         if err != nil {
219                 return nil, err
220         }
221
222         return createCoinbaseTxByReward(b.accountManager, b.block.Height, rewards)
223 }
224
225 func (b *blockBuilder) getTimeoutStatus() uint8 {
226         if b.timeoutStatus == timeoutCritical {
227                 return b.timeoutStatus
228         }
229
230         select {
231         case <-b.criticalTimeoutCh:
232                 b.timeoutStatus = timeoutCritical
233         case <-b.warnTimeoutCh:
234                 b.timeoutStatus = timeoutWarn
235         default:
236         }
237
238         return b.timeoutStatus
239 }
240
241 func createCoinbaseTxByReward(accountManager *account.Manager, blockHeight uint64, rewards []state.CoinbaseReward) (tx *types.Tx, err error) {
242         arbitrary := append([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...)
243         var script []byte
244         if accountManager == nil {
245                 script, err = vmutil.DefaultCoinbaseProgram()
246         } else {
247                 script, err = accountManager.GetCoinbaseControlProgram()
248                 arbitrary = append(arbitrary, accountManager.GetCoinbaseArbitrary()...)
249         }
250         if err != nil {
251                 return nil, err
252         }
253
254         if len(arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
255                 return nil, validation.ErrCoinbaseArbitraryOversize
256         }
257
258         builder := txbuilder.NewBuilder(time.Now())
259         if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
260                 return nil, err
261         }
262
263         if err = builder.AddOutput(types.NewIntraChainOutput(*consensus.BTMAssetID, 0, script)); err != nil {
264                 return nil, err
265         }
266
267         for _, r := range rewards {
268                 if err = builder.AddOutput(types.NewIntraChainOutput(*consensus.BTMAssetID, r.Amount, r.ControlProgram)); err != nil {
269                         return nil, err
270                 }
271         }
272
273         _, txData, err := builder.Build()
274         if err != nil {
275                 return nil, err
276         }
277
278         byteData, err := txData.MarshalText()
279         if err != nil {
280                 return nil, err
281         }
282
283         txData.SerializedSize = uint64(len(byteData))
284         tx = &types.Tx{
285                 TxData: *txData,
286                 Tx:     types.MapTx(txData),
287         }
288         return tx, nil
289 }
290
291 type validateTxResult struct {
292         tx      *types.Tx
293         gasOnly bool
294         err     error
295 }
296
297 func preValidateTxs(txs []*types.Tx, chain *protocol.Chain, view *state.UtxoViewpoint, gasLeft int64) ([]*validateTxResult, int64) {
298         var results []*validateTxResult
299         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: chain.BestBlockHeight() + 1}}
300         bcTxs := make([]*bc.Tx, len(txs))
301         for i, tx := range txs {
302                 bcTxs[i] = tx.Tx
303         }
304
305         validateResults := validation.ValidateTxs(bcTxs, bcBlock)
306         for i := 0; i < len(validateResults) && gasLeft > 0; i++ {
307                 gasOnlyTx := false
308                 gasStatus := validateResults[i].GetGasState()
309                 if err := validateResults[i].GetError(); err != nil {
310                         if !gasStatus.GasValid {
311                                 results = append(results, &validateTxResult{tx: txs[i], err: err})
312                                 continue
313                         }
314                         gasOnlyTx = true
315                 }
316
317                 if err := chain.GetTransactionsUtxo(view, []*bc.Tx{bcTxs[i]}); err != nil {
318                         results = append(results, &validateTxResult{tx: txs[i], err: err})
319                         continue
320                 }
321
322                 if gasLeft-gasStatus.GasUsed < 0 {
323                         break
324                 }
325
326                 if err := view.ApplyTransaction(bcBlock, bcTxs[i], gasOnlyTx); err != nil {
327                         results = append(results, &validateTxResult{tx: txs[i], err: err})
328                         continue
329                 }
330
331                 if err := validateBySubProtocols(txs[i], validateResults[i].GetError() != nil, chain.SubProtocols()); err != nil {
332                         results = append(results, &validateTxResult{tx: txs[i], err: err})
333                         continue
334                 }
335
336                 results = append(results, &validateTxResult{tx: txs[i], gasOnly: gasOnlyTx, err: validateResults[i].GetError()})
337                 gasLeft -= gasStatus.GasUsed
338         }
339         return results, gasLeft
340 }
341
342 func validateBySubProtocols(tx *types.Tx, statusFail bool, subProtocols []protocol.Protocoler) error {
343         for _, subProtocol := range subProtocols {
344                 verifyResult := &bc.TxVerifyResult{StatusFail: statusFail}
345                 if err := subProtocol.ValidateTx(tx, verifyResult); err != nil {
346                         return err
347                 }
348         }
349         return nil
350 }