OSDN Git Service

Merge pull request #935 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         byteData, err := txData.MarshalText()
54         if err != nil {
55                 return
56         }
57         txData.SerializedSize = uint64(len(byteData))
58
59         tx = &types.Tx{
60                 TxData: *txData,
61                 Tx:     types.MapTx(txData),
62         }
63         return
64 }
65
66 // NewBlockTemplate returns a new block template that is ready to be solved
67 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) (b *types.Block, err error) {
68         view := state.NewUtxoViewpoint()
69         txStatus := bc.NewTransactionStatus()
70         txStatus.SetStatus(0, false)
71         txEntries := []*bc.Tx{nil}
72         gasUsed := uint64(0)
73         txFee := uint64(0)
74
75         // get preblock info for generate next block
76         preBlockHeader := c.BestBlockHeader()
77         preBlockHash := preBlockHeader.Hash()
78         nextBlockHeight := preBlockHeader.Height + 1
79         nextBits, err := c.CalcNextBits(&preBlockHash)
80         if err != nil {
81                 return nil, err
82         }
83
84         b = &types.Block{
85                 BlockHeader: types.BlockHeader{
86                         Version:           1,
87                         Height:            nextBlockHeight,
88                         PreviousBlockHash: preBlockHash,
89                         Timestamp:         uint64(time.Now().Unix()),
90                         BlockCommitment:   types.BlockCommitment{},
91                         Bits:              nextBits,
92                 },
93         }
94         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
95         b.Transactions = []*types.Tx{nil}
96
97         txs := txPool.GetTransactions()
98         sort.Sort(ByTime(txs))
99         for _, txDesc := range txs {
100                 tx := txDesc.Tx.Tx
101                 gasOnlyTx := false
102
103                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
104                         log.WithField("error", err).Error("mining block generate skip tx due to")
105                         txPool.RemoveTransaction(&tx.ID)
106                         continue
107                 }
108
109                 gasStatus, err := validation.ValidateTx(tx, bcBlock)
110                 if err != nil {
111                         if !gasStatus.GasValid {
112                                 log.WithField("error", err).Error("mining block generate skip tx due to")
113                                 txPool.RemoveTransaction(&tx.ID)
114                                 continue
115                         }
116                         gasOnlyTx = true
117                 }
118
119                 if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
120                         break
121                 }
122
123                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
124                         log.WithField("error", err).Error("mining block generate skip tx due to")
125                         txPool.RemoveTransaction(&tx.ID)
126                         continue
127                 }
128
129                 txStatus.SetStatus(len(b.Transactions), gasOnlyTx)
130                 b.Transactions = append(b.Transactions, txDesc.Tx)
131                 txEntries = append(txEntries, tx)
132                 gasUsed += uint64(gasStatus.GasUsed)
133                 txFee += txDesc.Fee
134
135                 if gasUsed == consensus.MaxBlockGas {
136                         break
137                 }
138         }
139
140         // creater coinbase transaction
141         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
142         if err != nil {
143                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
144         }
145         txEntries[0] = b.Transactions[0].Tx
146
147         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.TxMerkleRoot(txEntries)
148         if err != nil {
149                 return nil, err
150         }
151
152         b.BlockHeader.BlockCommitment.TransactionStatusHash, err = bc.TxStatusMerkleRoot(txStatus.VerifyStatus)
153         return b, err
154 }