OSDN Git Service

35c021f06132c7c2bfa46196f4c5abbac3ac5857
[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) (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         _, txData, err := builder.Build()
53         if err != nil {
54                 return nil, err
55         }
56
57         tx = &types.Tx{
58                 TxData: *txData,
59                 Tx:     types.MapTx(txData),
60         }
61         return tx, nil
62 }
63
64 // restructCoinbaseTx build coinbase transaction with aggregate outputs when it achieved the specified block height
65 func restructCoinbaseTx(tx *types.Tx, rewards []state.CoinbaseReward) error {
66         for _, r := range rewards {
67                 tx.Outputs = append(tx.Outputs, types.NewIntraChainOutput(*consensus.BTMAssetID, r.Amount, r.ControlProgram))
68         }
69
70         byteData, err := tx.TxData.MarshalText()
71         if err != nil {
72                 return err
73         }
74
75         tx.TxData.SerializedSize = uint64(len(byteData))
76         tx.Tx = types.MapTx(&tx.TxData)
77         return 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, timestamp uint64) (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
90         // get preblock info for generate next block
91         preBlockHeader := c.BestBlockHeader()
92         preBlockHash := preBlockHeader.Hash()
93         nextBlockHeight := preBlockHeader.Height + 1
94
95         b = &types.Block{
96                 BlockHeader: types.BlockHeader{
97                         Version:           1,
98                         Height:            nextBlockHeight,
99                         PreviousBlockHash: preBlockHash,
100                         Timestamp:         timestamp,
101                         BlockCommitment:   types.BlockCommitment{},
102                         BlockWitness:      types.BlockWitness{Witness: make([][]byte, consensus.ActiveNetParams.NumOfConsensusNode)},
103                 },
104         }
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
111         consensusResult, err := c.GetConsensusResultByHash(&preBlockHash)
112         if err != nil {
113                 return nil, err
114         }
115
116         entriesTxs := []*bc.Tx{}
117         for _, txDesc := range txs {
118                 entriesTxs = append(entriesTxs, txDesc.Tx.Tx)
119         }
120
121         validateResults := validation.ValidateTxs(entriesTxs, bcBlock)
122         for i, validateResult := range validateResults {
123                 txDesc := txs[i]
124                 tx := txDesc.Tx.Tx
125                 gasOnlyTx := false
126
127                 gasStatus := validateResult.GetGasState()
128                 if validateResult.GetError() != nil {
129                         if !gasStatus.GasValid {
130                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
131                                 continue
132                         }
133                         gasOnlyTx = true
134                 }
135
136                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
137                         blkGenSkipTxForErr(txPool, &tx.ID, err)
138                         continue
139                 }
140
141                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.ActiveNetParams.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 := consensusResult.ApplyTransaction(txDesc.Tx); err != nil {
151                         blkGenSkipTxForErr(txPool, &tx.ID, err)
152                         continue
153                 }
154
155                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
156                         return nil, err
157                 }
158
159                 b.Transactions = append(b.Transactions, txDesc.Tx)
160                 txEntries = append(txEntries, tx)
161                 gasUsed += uint64(gasStatus.GasUsed)
162                 if gasUsed == consensus.ActiveNetParams.MaxBlockGas {
163                         break
164                 }
165
166         }
167
168         // create coinbase transaction
169         b.Transactions[0], err = createCoinbaseTx(accountManager, nextBlockHeight)
170         if err != nil {
171                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
172         }
173
174         if err := consensusResult.AttachCoinbaseReward(b); err != nil {
175                 return nil, err
176         }
177
178         rewards, err := consensusResult.GetCoinbaseRewards(nextBlockHeight)
179         if err != nil {
180                 return nil, err
181         }
182
183         // restruct coinbase transaction
184         if err = restructCoinbaseTx(b.Transactions[0], rewards); err != nil {
185                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
186         }
187
188         txEntries[0] = b.Transactions[0].Tx
189         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
190         if err != nil {
191                 return nil, err
192         }
193
194         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
195
196         _, err = c.SignBlock(b)
197         return b, err
198 }
199
200 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
201         log.WithFields(log.Fields{"module": logModule, "error": err}).Error("mining block generation: skip tx due to")
202         txPool.RemoveTransaction(txHash)
203 }