OSDN Git Service

319d0190373a83ec639d1289f2a5a2a9ce7043f9
[bytom/vapor.git] / proposal / proposal.go
1 package proposal
2
3 import (
4         "strconv"
5         "time"
6
7         log "github.com/sirupsen/logrus"
8
9         "github.com/vapor/account"
10         "github.com/vapor/blockchain/txbuilder"
11         "github.com/vapor/consensus"
12         "github.com/vapor/errors"
13         "github.com/vapor/protocol"
14         "github.com/vapor/protocol/bc"
15         "github.com/vapor/protocol/bc/types"
16         "github.com/vapor/protocol/state"
17         "github.com/vapor/protocol/validation"
18         "github.com/vapor/protocol/vm/vmutil"
19 )
20
21 const logModule = "mining"
22
23 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
24 // based on the passed block height to the provided address.  When the address
25 // is nil, the coinbase transaction will instead be redeemable by anyone.
26 func createCoinbaseTx(accountManager *account.Manager, blockHeight uint64, rewards []state.CoinbaseReward) (tx *types.Tx, err error) {
27         arbitrary := append([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...)
28         var script []byte
29         if accountManager == nil {
30                 script, err = vmutil.DefaultCoinbaseProgram()
31         } else {
32                 script, err = accountManager.GetCoinbaseControlProgram()
33                 arbitrary = append(arbitrary, accountManager.GetCoinbaseArbitrary()...)
34         }
35         if err != nil {
36                 return nil, err
37         }
38
39         if len(arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
40                 return nil, validation.ErrCoinbaseArbitraryOversize
41         }
42
43         builder := txbuilder.NewBuilder(time.Now())
44         if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
45                 return nil, err
46         }
47         if err = builder.AddOutput(types.NewIntraChainOutput(*consensus.BTMAssetID, 0, script)); err != nil {
48                 return nil, err
49         }
50
51         for _, r := range rewards {
52                 if err = builder.AddOutput(types.NewIntraChainOutput(*consensus.BTMAssetID, r.Amount, r.ControlProgram)); err != nil {
53                         return nil, err
54                 }
55         }
56
57         _, txData, err := builder.Build()
58         if err != nil {
59                 return nil, err
60         }
61
62         byteData, err := txData.MarshalText()
63         if err != nil {
64                 return nil, err
65         }
66
67         txData.SerializedSize = uint64(len(byteData))
68         tx = &types.Tx{
69                 TxData: *txData,
70                 Tx:     types.MapTx(txData),
71         }
72         return tx, nil
73 }
74
75 // NewBlockTemplate returns a new block template that is ready to be solved
76 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager, txs []*types.Tx, timestamp uint64) (b *types.Block, err error) {
77         view := state.NewUtxoViewpoint()
78         txStatus := bc.NewTransactionStatus()
79         if err := txStatus.SetStatus(0, false); err != nil {
80                 return nil, err
81         }
82         txEntries := []*bc.Tx{nil}
83         gasUsed := uint64(0)
84
85         // get preblock info for generate next block
86         preBlockHeader := c.BestBlockHeader()
87         preBlockHash := preBlockHeader.Hash()
88         nextBlockHeight := preBlockHeader.Height + 1
89
90         b = &types.Block{
91                 BlockHeader: types.BlockHeader{
92                         Version:           1,
93                         Height:            nextBlockHeight,
94                         PreviousBlockHash: preBlockHash,
95                         Timestamp:         timestamp,
96                         BlockCommitment:   types.BlockCommitment{},
97                         BlockWitness:      types.BlockWitness{Witness: make([][]byte, consensus.ActiveNetParams.NumOfConsensusNode)},
98                 },
99         }
100         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
101         b.Transactions = []*types.Tx{nil}
102
103         entriesTxs := []*bc.Tx{}
104         for _, tx := range txs {
105                 entriesTxs = append(entriesTxs, tx.Tx)
106         }
107
108         validateResults := validation.ValidateTxs(entriesTxs, bcBlock)
109         for i, validateResult := range validateResults {
110                 tx := txs[i].Tx
111                 gasOnlyTx := false
112
113                 gasStatus := validateResult.GetGasState()
114                 if validateResult.GetError() != nil {
115                         if !gasStatus.GasValid {
116                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
117                                 continue
118                         }
119                         gasOnlyTx = true
120                 }
121
122                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
123                         blkGenSkipTxForErr(txPool, &tx.ID, err)
124                         continue
125                 }
126
127                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.ActiveNetParams.MaxBlockGas {
128                         break
129                 }
130
131                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
132                         blkGenSkipTxForErr(txPool, &tx.ID, err)
133                         continue
134                 }
135
136                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
137                         return nil, err
138                 }
139
140                 b.Transactions = append(b.Transactions, txs[i])
141                 txEntries = append(txEntries, tx)
142                 gasUsed += uint64(gasStatus.GasUsed)
143                 if gasUsed == consensus.ActiveNetParams.MaxBlockGas {
144                         break
145                 }
146
147         }
148
149         consensusResult, err := c.GetConsensusResultByHash(&preBlockHash)
150         if err != nil {
151                 return nil, err
152         }
153
154         rewards, err := consensusResult.GetCoinbaseRewards(preBlockHeader.Height)
155         if err != nil {
156                 return nil, err
157         }
158
159         // create coinbase transaction
160         b.Transactions[0], err = createCoinbaseTx(accountManager, nextBlockHeight, rewards)
161         if err != nil {
162                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
163         }
164
165         txEntries[0] = b.Transactions[0].Tx
166         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
167         if err != nil {
168                 return nil, err
169         }
170
171         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
172
173         _, err = c.SignBlock(b)
174         return b, err
175 }
176
177 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
178         log.WithFields(log.Fields{"module": logModule, "error": err}).Error("mining block generation: skip tx due to")
179         txPool.RemoveTransaction(txHash)
180 }