OSDN Git Service

d2d045e82dc8cfa1dea7ee9a1e1d3215e01defa1
[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.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.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         entriesTxs := []*bc.Tx{}
112         for _, txDesc := range txs {
113                 entriesTxs = append(entriesTxs, txDesc.Tx.Tx)
114         }
115
116         validateResults := validation.ValidateTxs(entriesTxs, bcBlock)
117         for i, validateResult := range validateResults {
118                 txDesc := txs[i]
119                 tx := txDesc.Tx.Tx
120                 gasOnlyTx := false
121
122                 gasStatus := validateResult.GetGasState()
123                 if validateResult.GetError() != nil {
124                         if !gasStatus.GasValid {
125                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
126                                 continue
127                         }
128                         gasOnlyTx = true
129                 }
130
131                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
132                         blkGenSkipTxForErr(txPool, &tx.ID, err)
133                         continue
134                 }
135
136                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
137                         break
138                 }
139
140                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
141                         blkGenSkipTxForErr(txPool, &tx.ID, err)
142                         continue
143                 }
144
145                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
146                         return nil, err
147                 }
148
149                 b.Transactions = append(b.Transactions, txDesc.Tx)
150                 txEntries = append(txEntries, tx)
151                 gasUsed += uint64(gasStatus.GasUsed)
152                 if gasUsed == consensus.MaxBlockGas {
153                         break
154                 }
155
156         }
157
158         // create coinbase transaction
159         b.Transactions[0], err = createCoinbaseTx(accountManager, nextBlockHeight)
160         if err != nil {
161                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
162         }
163
164         consensusResult, err := c.GetConsensusResultByHash(&preBlockHash)
165         if err != nil {
166                 return nil, err
167         }
168
169         if err := consensusResult.AttachCoinbaseReward(b); err != nil {
170                 return nil, err
171         }
172
173         rewards, err := consensusResult.GetCoinbaseRewards(nextBlockHeight)
174         if err != nil {
175                 return nil, err
176         }
177
178         // restruct coinbase transaction
179         if err = restructCoinbaseTx(b.Transactions[0], rewards); err != nil {
180                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
181         }
182
183         txEntries[0] = b.Transactions[0].Tx
184         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
185         if err != nil {
186                 return nil, err
187         }
188
189         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
190
191         _, err = c.SignBlock(b)
192         return b, err
193 }
194
195 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
196         log.WithFields(log.Fields{"module": logModule, "error": err}).Error("mining block generation: skip tx due to")
197         txPool.RemoveTransaction(txHash)
198 }