OSDN Git Service

Merge pull request #341 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/blockchain/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/legacy"
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 *legacy.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(legacy.NewCoinbaseInput([]byte(string(blockHeight)), nil), &txbuilder.SigningInstruction{}); err != nil {
44                 return
45         }
46         if err = builder.AddOutput(legacy.NewTxOutput(*consensus.BTMAssetID, amount, script, nil)); err != nil {
47                 return
48         }
49         _, txData, err := builder.Build()
50         if err != nil {
51                 return
52         }
53
54         tx = &legacy.Tx{
55                 TxData: *txData,
56                 Tx:     legacy.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 *legacy.Block, err error) {
63         view := state.NewUtxoViewpoint()
64         txEntries := []*bc.Tx{nil}
65         blockWeight := uint64(0)
66         txFee := uint64(0)
67
68         // get preblock info for generate next block
69         preBlock := c.BestBlock()
70         preBcBlock := legacy.MapBlock(preBlock)
71         nextBlockHeight := preBlock.BlockHeader.Height + 1
72
73         var compareDiffBH *legacy.BlockHeader
74         if compareDiffBlock, err := c.GetBlockByHeight(nextBlockHeight - consensus.BlocksPerRetarget); err == nil {
75                 compareDiffBH = &compareDiffBlock.BlockHeader
76         }
77
78         b = &legacy.Block{
79                 BlockHeader: legacy.BlockHeader{
80                         Version:           1,
81                         Height:            nextBlockHeight,
82                         PreviousBlockHash: preBlock.Hash(),
83                         Timestamp:         uint64(time.Now().Unix()),
84                         TransactionStatus: *bc.NewTransactionStatus(),
85                         BlockCommitment:   legacy.BlockCommitment{},
86                         Bits:              difficulty.CalcNextRequiredDifficulty(&preBlock.BlockHeader, compareDiffBH),
87                 },
88                 Transactions: []*legacy.Tx{nil},
89         }
90         bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
91
92         txs := txPool.GetTransactions()
93         sort.Sort(ByTime(txs))
94         for _, txDesc := range txs {
95                 tx := txDesc.Tx.Tx
96                 gasOnlyTx := false
97                 if blockWeight+txDesc.Weight > consensus.MaxBlockSzie-consensus.MaxTxSize {
98                         break
99                 }
100
101                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
102                         log.WithField("error", err).Error("mining block generate skip tx due to")
103                         txPool.RemoveTransaction(&tx.ID)
104                         continue
105                 }
106
107                 if _, gasVaild, err := validation.ValidateTx(tx, preBcBlock); err != nil {
108                         if !gasVaild {
109                                 log.WithField("error", err).Error("mining block generate skip tx due to")
110                                 txPool.RemoveTransaction(&tx.ID)
111                                 continue
112                         }
113                         gasOnlyTx = true
114                 }
115
116                 if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
117                         log.WithField("error", err).Error("mining block generate skip tx due to")
118                         txPool.RemoveTransaction(&tx.ID)
119                         continue
120                 }
121
122                 b.BlockHeader.TransactionStatus.SetStatus(len(b.Transactions), gasOnlyTx)
123                 b.Transactions = append(b.Transactions, txDesc.Tx)
124                 txEntries = append(txEntries, tx)
125                 blockWeight += txDesc.Weight
126                 txFee += txDesc.Fee
127         }
128
129         // creater coinbase transaction
130         b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
131         if err != nil {
132                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
133         }
134         txEntries[0] = b.Transactions[0].Tx
135
136         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.MerkleRoot(txEntries)
137         return b, err
138 }