OSDN Git Service

Add docs
[bytom/vapor.git] / mining / mining.go
1 package mining
2
3 import (
4         "encoding/binary"
5         "encoding/json"
6         "sort"
7         "strconv"
8         "time"
9
10         "github.com/vapor/protocol/vm"
11
12         "github.com/vapor/common"
13
14         log "github.com/sirupsen/logrus"
15
16         "github.com/vapor/account"
17         "github.com/vapor/blockchain/txbuilder"
18         "github.com/vapor/config"
19         "github.com/vapor/consensus"
20         engine "github.com/vapor/consensus/consensus"
21         dpos "github.com/vapor/consensus/consensus/dpos"
22         "github.com/vapor/crypto/ed25519/chainkd"
23         "github.com/vapor/errors"
24         "github.com/vapor/protocol"
25         "github.com/vapor/protocol/bc"
26         "github.com/vapor/protocol/bc/types"
27         "github.com/vapor/protocol/state"
28         "github.com/vapor/protocol/validation"
29         "github.com/vapor/protocol/vm/vmutil"
30 )
31
32 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
33 // based on the passed block height to the provided address.  When the address
34 // is nil, the coinbase transaction will instead be redeemable by anyone.
35 func createCoinbaseTx(accountManager *account.Manager, amount uint64, blockHeight uint64, delegateInfo interface{}, timestamp uint64) (tx *types.Tx, err error) {
36         //amount += consensus.BlockSubsidy(blockHeight)
37         arbitrary := append([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...)
38
39         var script []byte
40         address, _ := common.DecodeAddress(config.CommonConfig.Consensus.Coinbase, &consensus.ActiveNetParams)
41         redeemContract := address.ScriptAddress()
42         script, _ = vmutil.P2WPKHProgram(redeemContract)
43
44         if err != nil {
45                 return nil, err
46         }
47
48         if len(arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
49                 return nil, validation.ErrCoinbaseArbitraryOversize
50         }
51
52         builder := txbuilder.NewBuilder(time.Now())
53         if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
54                 return nil, err
55         }
56
57         if err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {
58                 return nil, err
59         }
60         _, txData, err := builder.Build()
61         if err != nil {
62                 return nil, err
63         }
64
65         delegates := dpos.DelegateInfoList{}
66         if delegateInfo != nil {
67                 tmp := delegateInfo.(*dpos.DelegateInfo)
68                 delegates.Delegate = *tmp
69         }
70
71         var xPrv chainkd.XPrv
72         if config.CommonConfig.Consensus.XPrv == "" {
73                 return nil, errors.New("Signer is empty")
74         }
75         xPrv.UnmarshalText([]byte(config.CommonConfig.Consensus.XPrv))
76
77         buf := [8]byte{}
78         binary.LittleEndian.PutUint64(buf[:], timestamp)
79         delegates.SigTime = xPrv.Sign(buf[:])
80         delegates.Xpub = xPrv.XPub()
81
82         data, err := json.Marshal(&delegates)
83         if err != nil {
84                 return nil, err
85         }
86
87         msg := dpos.DposMsg{
88                 Type: vm.OP_DELEGATE,
89                 Data: data,
90         }
91
92         data, err = json.Marshal(&msg)
93         if err != nil {
94                 return nil, err
95         }
96         txData.ReferenceData = data
97
98         byteData, err := txData.MarshalText()
99         if err != nil {
100                 return nil, err
101         }
102         txData.SerializedSize = uint64(len(byteData))
103
104         tx = &types.Tx{
105                 TxData: *txData,
106                 Tx:     types.MapTx(txData),
107         }
108         return tx, nil
109 }
110
111 // NewBlockTemplate returns a new block template that is ready to be solved
112 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager, engine engine.Engine, delegateInfo interface{}, blockTime uint64) (b *types.Block, err error) {
113         view := state.NewUtxoViewpoint()
114         txStatus := bc.NewTransactionStatus()
115         if err := txStatus.SetStatus(0, false); err != nil {
116                 return nil, err
117         }
118         txEntries := []*bc.Tx{nil}
119         gasUsed := uint64(0)
120         txFee := uint64(0)
121
122         // get preblock info for generate next block
123         preBlockHeader := c.BestBlockHeader()
124         preBlockHash := preBlockHeader.Hash()
125         nextBlockHeight := preBlockHeader.Height + 1
126
127         header := types.BlockHeader{
128                 Version:           1,
129                 Height:            nextBlockHeight,
130                 PreviousBlockHash: preBlockHash,
131                 Timestamp:         blockTime,
132                 BlockCommitment:   types.BlockCommitment{},
133         }
134
135         b = &types.Block{}
136         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
137         b.Transactions = []*types.Tx{nil}
138
139         txs := txPool.GetTransactions()
140         sort.Sort(byTime(txs))
141         for _, txDesc := range txs {
142                 tx := txDesc.Tx.Tx
143                 gasOnlyTx := false
144
145                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
146                         blkGenSkipTxForErr(txPool, &tx.ID, err)
147                         continue
148                 }
149                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
150                 if err != nil {
151                         if !gasStatus.GasValid {
152                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
153                                 continue
154                         }
155                         gasOnlyTx = true
156                 }
157
158                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
159                         break
160                 }
161
162                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
163                         blkGenSkipTxForErr(txPool, &tx.ID, err)
164                         continue
165                 }
166
167                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
168                         return nil, err
169                 }
170
171                 b.Transactions = append(b.Transactions, txDesc.Tx)
172                 txEntries = append(txEntries, tx)
173                 gasUsed += uint64(gasStatus.GasUsed)
174                 txFee += txDesc.Fee
175                 if gasUsed == consensus.MaxBlockGas {
176                         break
177                 }
178         }
179
180         b.BlockHeader = header
181         // creater coinbase transaction
182         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight, delegateInfo, b.Timestamp)
183         if err != nil {
184                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
185         }
186         txEntries[0] = b.Transactions[0].Tx
187
188         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
189         if err != nil {
190                 return nil, err
191         }
192
193         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
194         return b, err
195 }
196
197 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
198         log.WithField("error", err).Error("mining block generation: skip tx due to")
199         txPool.RemoveTransaction(txHash)
200 }