OSDN Git Service

Merge pull request #37 from Bytom/dev
[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         byteData, err := txData.MarshalText()
66         if err != nil {
67                 return nil, err
68         }
69         txData.SerializedSize = uint64(len(byteData))
70         delegates := dpos.DelegateInfoList{}
71         if delegateInfo != nil {
72                 tmp := delegateInfo.(*dpos.DelegateInfo)
73                 delegates.Delegate = *tmp
74         }
75
76         var xPrv chainkd.XPrv
77         if config.CommonConfig.Consensus.XPrv == "" {
78                 return nil, errors.New("Signer is empty")
79         }
80         xPrv.UnmarshalText([]byte(config.CommonConfig.Consensus.XPrv))
81
82         buf := [8]byte{}
83         binary.LittleEndian.PutUint64(buf[:], timestamp)
84         delegates.SigTime = xPrv.Sign(buf[:])
85         delegates.Xpub = xPrv.XPub()
86
87         data, err := json.Marshal(&delegates)
88         if err != nil {
89                 return nil, err
90         }
91
92         msg := dpos.DposMsg{
93                 Type: vm.OP_DELEGATE,
94                 Data: data,
95         }
96
97         data, err = json.Marshal(&msg)
98         if err != nil {
99                 return nil, err
100         }
101         txData.ReferenceData = data
102
103         tx = &types.Tx{
104                 TxData: *txData,
105                 Tx:     types.MapTx(txData),
106         }
107         return tx, nil
108 }
109
110 // NewBlockTemplate returns a new block template that is ready to be solved
111 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager, engine engine.Engine, delegateInfo interface{}, blockTime uint64) (b *types.Block, err error) {
112         view := state.NewUtxoViewpoint()
113         txStatus := bc.NewTransactionStatus()
114         if err := txStatus.SetStatus(0, false); err != nil {
115                 return nil, err
116         }
117         txEntries := []*bc.Tx{nil}
118         gasUsed := uint64(0)
119         txFee := uint64(0)
120
121         // get preblock info for generate next block
122         preBlockHeader := c.BestBlockHeader()
123         preBlockHash := preBlockHeader.Hash()
124         nextBlockHeight := preBlockHeader.Height + 1
125
126         header := types.BlockHeader{
127                 Version:           1,
128                 Height:            nextBlockHeight,
129                 PreviousBlockHash: preBlockHash,
130                 Timestamp:         blockTime,
131                 BlockCommitment:   types.BlockCommitment{},
132         }
133
134         b = &types.Block{}
135         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
136         b.Transactions = []*types.Tx{nil}
137
138         txs := txPool.GetTransactions()
139         sort.Sort(byTime(txs))
140         for _, txDesc := range txs {
141                 tx := txDesc.Tx.Tx
142                 gasOnlyTx := false
143
144                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
145                         blkGenSkipTxForErr(txPool, &tx.ID, err)
146                         continue
147                 }
148                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
149                 if err != nil {
150                         if !gasStatus.GasValid {
151                                 blkGenSkipTxForErr(txPool, &tx.ID, err)
152                                 continue
153                         }
154                         gasOnlyTx = true
155                 }
156
157                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
158                         break
159                 }
160
161                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
162                         blkGenSkipTxForErr(txPool, &tx.ID, err)
163                         continue
164                 }
165
166                 if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
167                         return nil, err
168                 }
169
170                 b.Transactions = append(b.Transactions, txDesc.Tx)
171                 txEntries = append(txEntries, tx)
172                 gasUsed += uint64(gasStatus.GasUsed)
173                 txFee += txDesc.Fee
174                 if gasUsed == consensus.MaxBlockGas {
175                         break
176                 }
177         }
178
179         b.BlockHeader = header
180         // creater coinbase transaction
181         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight, delegateInfo, b.Timestamp)
182         if err != nil {
183                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
184         }
185         txEntries[0] = b.Transactions[0].Tx
186
187         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.TxMerkleRoot(txEntries)
188         if err != nil {
189                 return nil, err
190         }
191
192         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
193         return b, err
194 }
195
196 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
197         log.WithField("error", err).Error("mining block generation: skip tx due to")
198         txPool.RemoveTransaction(txHash)
199 }