OSDN Git Service

init push for easy code review (#121)
[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, amount uint64, blockHeight uint64) (tx *types.Tx, err error) {
28         amount += consensus.BlockSubsidy(blockHeight)
29         arbitrary := append([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...)
30
31         var script []byte
32         if accountManager == nil {
33                 script, err = vmutil.DefaultCoinbaseProgram()
34         } else {
35                 script, err = accountManager.GetCoinbaseControlProgram()
36                 arbitrary = append(arbitrary, accountManager.GetCoinbaseArbitrary()...)
37         }
38         if err != nil {
39                 return nil, err
40         }
41
42         if len(arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
43                 return nil, validation.ErrCoinbaseArbitraryOversize
44         }
45
46         builder := txbuilder.NewBuilder(time.Now())
47         if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
48                 return nil, err
49         }
50         if err = builder.AddOutput(types.NewIntraChainOutput(*consensus.BTMAssetID, amount, script)); err != nil {
51                 return nil, err
52         }
53         _, txData, err := builder.Build()
54         if err != nil {
55                 return nil, err
56         }
57
58         byteData, err := txData.MarshalText()
59         if err != nil {
60                 return nil, err
61         }
62         txData.SerializedSize = uint64(len(byteData))
63
64         tx = &types.Tx{
65                 TxData: *txData,
66                 Tx:     types.MapTx(txData),
67         }
68         return tx, nil
69 }
70
71 // NewBlockTemplate returns a new block template that is ready to be solved
72 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager, timestamp uint64) (b *types.Block, err error) {
73         view := state.NewUtxoViewpoint()
74         txStatus := bc.NewTransactionStatus()
75         if err := txStatus.SetStatus(0, false); err != nil {
76                 return nil, err
77         }
78         txEntries := []*bc.Tx{nil}
79         gasUsed := uint64(0)
80         txFee := uint64(0)
81
82         // get preblock info for generate next block
83         preBlockHeader := c.BestBlockHeader()
84         preBlockHash := preBlockHeader.Hash()
85         nextBlockHeight := preBlockHeader.Height + 1
86
87         b = &types.Block{
88                 BlockHeader: types.BlockHeader{
89                         Version:           1,
90                         Height:            nextBlockHeight,
91                         PreviousBlockHash: preBlockHash,
92                         Timestamp:         timestamp,
93                         BlockCommitment:   types.BlockCommitment{},
94                         BlockWitness:      types.BlockWitness{Witness: make([][]byte, consensus.NumOfConsensusNode)},
95                 },
96         }
97         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
98         b.Transactions = []*types.Tx{nil}
99
100         txs := txPool.GetTransactions()
101         sort.Sort(byTime(txs))
102         for _, txDesc := range txs {
103                 tx := txDesc.Tx.Tx
104                 gasOnlyTx := false
105
106                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
107                         blkGenSkipTxForErr(txPool, &tx.ID, err)
108                         continue
109                 }
110
111                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
112                 if err != nil {
113                         if !gasStatus.GasValid {
114                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
115                                 continue
116                         }
117                         gasOnlyTx = true
118                 }
119
120                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
121                         break
122                 }
123
124                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
125                         blkGenSkipTxForErr(txPool, &tx.ID, err)
126                         continue
127                 }
128
129                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
130                         return nil, err
131                 }
132
133                 b.Transactions = append(b.Transactions, txDesc.Tx)
134                 txEntries = append(txEntries, tx)
135                 gasUsed += uint64(gasStatus.GasUsed)
136                 txFee += txDesc.Fee
137
138                 if gasUsed == consensus.MaxBlockGas {
139                         break
140                 }
141         }
142
143         // creater coinbase transaction
144         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
145         if err != nil {
146                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
147         }
148         txEntries[0] = b.Transactions[0].Tx
149
150         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
151         if err != nil {
152                 return nil, err
153         }
154
155         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
156
157         _, err = c.SignBlock(b)
158         return b, err
159 }
160
161 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
162         log.WithFields(log.Fields{"module": logModule, "error": err}).Error("mining block generation: skip tx due to")
163         txPool.RemoveTransaction(txHash)
164 }