OSDN Git Service

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