OSDN Git Service

fix the bug (#372)
[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/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 const logModule = "mining"
23
24 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
25 // based on the passed block height to the provided address.  When the address
26 // is nil, the coinbase transaction will instead be redeemable by anyone.
27 func createCoinbaseTx(accountManager *account.Manager, blockHeight uint64, rewards []state.CoinbaseReward) (tx *types.Tx, err error) {
28         arbitrary := append([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...)
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.ActiveNetParams.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.NewIntraChainOutput(*consensus.BTMAssetID, 0, script)); err != nil {
49                 return nil, err
50         }
51
52         for _, r := range rewards {
53                 if err = builder.AddOutput(types.NewIntraChainOutput(*consensus.BTMAssetID, r.Amount, r.ControlProgram)); err != nil {
54                         return nil, err
55                 }
56         }
57
58         _, txData, err := builder.Build()
59         if err != nil {
60                 return nil, err
61         }
62
63         byteData, err := txData.MarshalText()
64         if err != nil {
65                 return nil, err
66         }
67
68         txData.SerializedSize = uint64(len(byteData))
69         tx = &types.Tx{
70                 TxData: *txData,
71                 Tx:     types.MapTx(txData),
72         }
73         return tx, nil
74 }
75
76 // NewBlockTemplate returns a new block template that is ready to be solved
77 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager, timestamp uint64) (b *types.Block, err error) {
78         view := state.NewUtxoViewpoint()
79         txStatus := bc.NewTransactionStatus()
80         if err := txStatus.SetStatus(0, false); err != nil {
81                 return nil, err
82         }
83         txEntries := []*bc.Tx{nil}
84         gasUsed := uint64(0)
85
86         // get preblock info for generate next block
87         preBlockHeader := c.BestBlockHeader()
88         preBlockHash := preBlockHeader.Hash()
89         nextBlockHeight := preBlockHeader.Height + 1
90
91         b = &types.Block{
92                 BlockHeader: types.BlockHeader{
93                         Version:           1,
94                         Height:            nextBlockHeight,
95                         PreviousBlockHash: preBlockHash,
96                         Timestamp:         timestamp,
97                         BlockCommitment:   types.BlockCommitment{},
98                         BlockWitness:      types.BlockWitness{Witness: make([][]byte, consensus.ActiveNetParams.NumOfConsensusNode)},
99                 },
100         }
101         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
102         b.Transactions = []*types.Tx{nil}
103
104         txs := txPool.GetTransactions()
105         sort.Sort(byTime(txs))
106
107         entriesTxs := []*bc.Tx{}
108         for _, txDesc := range txs {
109                 entriesTxs = append(entriesTxs, txDesc.Tx.Tx)
110         }
111
112         validateResults := validation.ValidateTxs(entriesTxs, bcBlock)
113         for i, validateResult := range validateResults {
114                 txDesc := txs[i]
115                 tx := txDesc.Tx.Tx
116                 gasOnlyTx := false
117
118                 gasStatus := validateResult.GetGasState()
119                 if validateResult.GetError() != nil {
120                         if !gasStatus.GasValid {
121                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
122                                 continue
123                         }
124                         gasOnlyTx = true
125                 }
126
127                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
128                         blkGenSkipTxForErr(txPool, &tx.ID, err)
129                         continue
130                 }
131
132                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.ActiveNetParams.MaxBlockGas {
133                         break
134                 }
135
136                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
137                         blkGenSkipTxForErr(txPool, &tx.ID, err)
138                         continue
139                 }
140
141                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
142                         return nil, err
143                 }
144
145                 b.Transactions = append(b.Transactions, txDesc.Tx)
146                 txEntries = append(txEntries, tx)
147                 gasUsed += uint64(gasStatus.GasUsed)
148                 if gasUsed == consensus.ActiveNetParams.MaxBlockGas {
149                         break
150                 }
151
152         }
153
154         consensusResult, err := c.GetConsensusResultByHash(&preBlockHash)
155         if err != nil {
156                 return nil, err
157         }
158
159         rewards, err := consensusResult.GetCoinbaseRewards(preBlockHeader.Height)
160         if err != nil {
161                 return nil, err
162         }
163
164         // create coinbase transaction
165         b.Transactions[0], err = createCoinbaseTx(accountManager, nextBlockHeight, rewards)
166         if err != nil {
167                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
168         }
169
170         txEntries[0] = b.Transactions[0].Tx
171         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
172         if err != nil {
173                 return nil, err
174         }
175
176         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
177
178         _, err = c.SignBlock(b)
179         return b, err
180 }
181
182 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
183         log.WithFields(log.Fields{"module": logModule, "error": err}).Error("mining block generation: skip tx due to")
184         txPool.RemoveTransaction(txHash)
185 }