OSDN Git Service

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