OSDN Git Service

Merge pull request #519 from Bytom/dev
[bytom/bytom.git] / mining / mining.go
1 // Copyright (c) 2014-2016 The btcsuite developers
2 // Use of this source code is governed by an ISC
3 // license that can be found in the LICENSE file.
4
5 package mining
6
7 import (
8         "sort"
9         "time"
10
11         log "github.com/sirupsen/logrus"
12
13         "github.com/bytom/account"
14         "github.com/bytom/blockchain/txbuilder"
15         "github.com/bytom/consensus"
16         "github.com/bytom/consensus/difficulty"
17         "github.com/bytom/errors"
18         "github.com/bytom/protocol"
19         "github.com/bytom/protocol/bc"
20         "github.com/bytom/protocol/bc/types"
21         "github.com/bytom/protocol/state"
22         "github.com/bytom/protocol/validation"
23         "github.com/bytom/protocol/vm/vmutil"
24 )
25
26 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
27 // based on the passed block height to the provided address.  When the address
28 // is nil, the coinbase transaction will instead be redeemable by anyone.
29 func createCoinbaseTx(accountManager *account.Manager, amount uint64, blockHeight uint64) (tx *types.Tx, err error) {
30         amount += consensus.BlockSubsidy(blockHeight)
31
32         var script []byte
33         if accountManager == nil {
34                 script, err = vmutil.DefaultCoinbaseProgram()
35         } else {
36                 script, err = accountManager.GetCoinbaseControlProgram()
37         }
38         if err != nil {
39                 return
40         }
41
42         builder := txbuilder.NewBuilder(time.Now())
43         if err = builder.AddInput(types.NewCoinbaseInput([]byte(string(blockHeight))), &txbuilder.SigningInstruction{}); err != nil {
44                 return
45         }
46         if err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {
47                 return
48         }
49         _, txData, err := builder.Build()
50         if err != nil {
51                 return
52         }
53
54         tx = &types.Tx{
55                 TxData: *txData,
56                 Tx:     types.MapTx(txData),
57         }
58         return
59 }
60
61 // NewBlockTemplate returns a new block template that is ready to be solved
62 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) (b *types.Block, err error) {
63         view := state.NewUtxoViewpoint()
64         txStatus := bc.NewTransactionStatus()
65         txStatus.SetStatus(0, false)
66         txEntries := []*bc.Tx{nil}
67         gasUsed := uint64(0)
68         txFee := uint64(0)
69
70         // get preblock info for generate next block
71         preBlock := c.BestBlock()
72         preBcBlock := types.MapBlock(preBlock)
73         nextBlockHeight := preBlock.Height + 1
74
75         var compareDiffBH *types.BlockHeader
76         if compareDiffBlock, err := c.GetBlockByHeight(preBlock.Height - consensus.BlocksPerRetarget); err == nil {
77                 compareDiffBH = &compareDiffBlock.BlockHeader
78         }
79
80         b = &types.Block{
81                 BlockHeader: types.BlockHeader{
82                         Version:           1,
83                         Height:            nextBlockHeight,
84                         PreviousBlockHash: preBlock.Hash(),
85                         Timestamp:         uint64(time.Now().Unix()),
86                         BlockCommitment:   types.BlockCommitment{},
87                         Bits:              difficulty.CalcNextRequiredDifficulty(&preBlock.BlockHeader, compareDiffBH),
88                 },
89                 Transactions: []*types.Tx{nil},
90         }
91         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
92
93         txs := txPool.GetTransactions()
94         sort.Sort(ByTime(txs))
95         for _, txDesc := range txs {
96                 tx := txDesc.Tx.Tx
97                 gasOnlyTx := false
98
99                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
100                         log.WithField("error", err).Error("mining block generate skip tx due to")
101                         txPool.RemoveTransaction(&tx.ID)
102                         continue
103                 }
104
105                 gasStatus, err := validation.ValidateTx(tx, preBcBlock)
106                 if err != nil {
107                         if !gasStatus.GasVaild {
108                                 log.WithField("error", err).Error("mining block generate skip tx due to")
109                                 txPool.RemoveTransaction(&tx.ID)
110                                 continue
111                         }
112                         gasOnlyTx = true
113                 }
114
115                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
116                         break
117                 }
118
119                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
120                         log.WithField("error", err).Error("mining block generate skip tx due to")
121                         txPool.RemoveTransaction(&tx.ID)
122                         continue
123                 }
124
125                 txStatus.SetStatus(len(b.Transactions), gasOnlyTx)
126                 b.Transactions = append(b.Transactions, txDesc.Tx)
127                 txEntries = append(txEntries, tx)
128                 gasUsed += uint64(gasStatus.GasUsed)
129                 txFee += txDesc.Fee
130
131                 if gasUsed == consensus.MaxBlockGas {
132                         break
133                 }
134         }
135
136         // creater coinbase transaction
137         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
138         if err != nil {
139                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
140         }
141         txEntries[0] = b.Transactions[0].Tx
142
143         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.TxMerkleRoot(txEntries)
144         if err != nil {
145                 return nil, err
146         }
147
148         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = bc.TxStatusMerkleRoot(txStatus.VerifyStatus)
149         return b, err
150 }