OSDN Git Service

V0.1 federation parse (#89)
[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) (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:         uint64(time.Now().UnixNano() / int64(time.Millisecond)),
93                         BlockCommitment:   types.BlockCommitment{},
94                 },
95         }
96         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
97         b.Transactions = []*types.Tx{nil}
98
99         txs := txPool.GetTransactions()
100         sort.Sort(byTime(txs))
101         for _, txDesc := range txs {
102                 tx := txDesc.Tx.Tx
103                 gasOnlyTx := false
104
105                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
106                         blkGenSkipTxForErr(txPool, &tx.ID, err)
107                         continue
108                 }
109
110                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
111                 if err != nil {
112                         if !gasStatus.GasValid {
113                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
114                                 continue
115                         }
116                         gasOnlyTx = true
117                 }
118
119                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
120                         break
121                 }
122
123                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
124                         blkGenSkipTxForErr(txPool, &tx.ID, err)
125                         continue
126                 }
127
128                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
129                         return nil, err
130                 }
131
132                 b.Transactions = append(b.Transactions, txDesc.Tx)
133                 txEntries = append(txEntries, tx)
134                 gasUsed += uint64(gasStatus.GasUsed)
135                 txFee += txDesc.Fee
136
137                 if gasUsed == consensus.MaxBlockGas {
138                         break
139                 }
140         }
141
142         // creater coinbase transaction
143         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
144         if err != nil {
145                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
146         }
147         txEntries[0] = b.Transactions[0].Tx
148
149         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
150         if err != nil {
151                 return nil, err
152         }
153
154         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
155
156         _, err = c.GetBBFT().SignBlock(b)
157         return b, err
158 }
159
160 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
161         log.WithFields(log.Fields{"module": logModule, "error": err}).Error("mining block generation: skip tx due to")
162         txPool.RemoveTransaction(txHash)
163 }