OSDN Git Service

Merge pull request #236 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         "time"
9
10         log "github.com/sirupsen/logrus"
11
12         "github.com/bytom/blockchain/account"
13         "github.com/bytom/blockchain/txbuilder"
14         "github.com/bytom/consensus"
15         "github.com/bytom/consensus/algorithm"
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         unlockHeight := blockHeight + consensus.CoinbasePendingBlockNumber
32
33         var script []byte
34         if accountManager == nil {
35                 script, err = vmutil.CoinbaseProgram(nil, 0, unlockHeight)
36         } else {
37                 script, err = accountManager.GetCoinbaseControlProgram(unlockHeight)
38         }
39         if err != nil {
40                 return
41         }
42
43         builder := txbuilder.NewBuilder(time.Now())
44         builder.AddOutput(legacy.NewTxOutput(*consensus.BTMAssetID, amount, script, nil))
45         _, txData, err := builder.Build()
46         if err != nil {
47                 return
48         }
49
50         tx = &legacy.Tx{
51                 TxData: *txData,
52                 Tx:     legacy.MapTx(txData),
53         }
54         return
55 }
56
57 // NewBlockTemplate returns a new block template that is ready to be solved
58 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) (*legacy.Block, error) {
59         // Extend the most recently known best block.
60         var err error
61         preBlock := c.BestBlock()
62         view := state.NewUtxoViewpoint()
63
64         preBcBlock := legacy.MapBlock(preBlock)
65         nextBlockHeight := preBlock.BlockHeader.Height + 1
66         nextBlockSeed := algorithm.CreateSeed(nextBlockHeight, preBcBlock.Seed, []*bc.Hash{&preBcBlock.ID})
67         txDescs := txPool.GetTransactions()
68         txEntries := make([]*bc.Tx, 0, len(txDescs))
69         blockWeight := uint64(0)
70         txFee := uint64(0)
71
72         var compareDiffBH *legacy.BlockHeader
73         if compareDiffBlock, err := c.GetBlockByHeight(nextBlockHeight - consensus.BlocksPerRetarget); err == nil {
74                 compareDiffBH = &compareDiffBlock.BlockHeader
75         }
76
77         b := &legacy.Block{
78                 BlockHeader: legacy.BlockHeader{
79                         Version:           1,
80                         Height:            nextBlockHeight,
81                         PreviousBlockHash: preBlock.Hash(),
82                         Seed:              *nextBlockSeed,
83                         TimestampMS:       bc.Millis(time.Now()),
84                         BlockCommitment:   legacy.BlockCommitment{},
85                         Bits:              difficulty.CalcNextRequiredDifficulty(&preBlock.BlockHeader, compareDiffBH),
86                 },
87                 Transactions: make([]*legacy.Tx, 0, len(txDescs)),
88         }
89
90         appendTx := func(tx *legacy.Tx, weight, fee uint64) {
91                 b.Transactions = append([]*legacy.Tx{tx}, b.Transactions...)
92                 txEntries = append([]*bc.Tx{tx.Tx}, txEntries...)
93                 blockWeight += weight
94                 txFee += fee
95         }
96
97         bcBlock := legacy.MapBlock(b)
98         for _, txDesc := range txDescs {
99                 tx := txDesc.Tx.Tx
100                 if blockWeight+txDesc.Weight > consensus.MaxBlockSzie-consensus.MaxTxSize {
101                         break
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                 if err := view.ApplyTransaction(bcBlock, tx); err != nil {
109                         log.WithField("error", err).Error("mining block generate skip tx due to")
110                         txPool.RemoveTransaction(&tx.ID)
111                         continue
112                 }
113                 if _, err := validation.ValidateTx(tx, preBcBlock); err != nil {
114                         log.WithField("error", err).Error("mining block generate skip tx due to")
115                         txPool.RemoveTransaction(&tx.ID)
116                         continue
117                 }
118
119                 appendTx(txDesc.Tx, txDesc.Weight, txDesc.Fee)
120         }
121
122         cbTx, err := createCoinbaseTx(accountManager, txFee, nextBlockHeight)
123         if err != nil {
124                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
125         }
126         appendTx(cbTx, 0, 0)
127
128         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.MerkleRoot(txEntries)
129         if err != nil {
130                 return nil, errors.Wrap(err, "calculating tx merkle root")
131         }
132
133         return b, nil
134 }