OSDN Git Service

Coinbase input (#290)
[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         if err = builder.AddInput(legacy.NewCoinbaseInput([]byte(string(blockHeight)), nil), &txbuilder.SigningInstruction{}); err != nil {
45                 return
46         }
47         if err = builder.AddOutput(legacy.NewTxOutput(*consensus.BTMAssetID, amount, script, nil)); err != nil {
48                 return
49         }
50         _, txData, err := builder.Build()
51         if err != nil {
52                 return
53         }
54
55         tx = &legacy.Tx{
56                 TxData: *txData,
57                 Tx:     legacy.MapTx(txData),
58         }
59         return
60 }
61
62 // NewBlockTemplate returns a new block template that is ready to be solved
63 func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) (*legacy.Block, error) {
64         // Extend the most recently known best block.
65         var err error
66         preBlock := c.BestBlock()
67         view := state.NewUtxoViewpoint()
68
69         preBcBlock := legacy.MapBlock(preBlock)
70         nextBlockHeight := preBlock.BlockHeader.Height + 1
71         nextBlockSeed := algorithm.CreateSeed(nextBlockHeight, preBcBlock.Seed, []*bc.Hash{&preBcBlock.ID})
72         txDescs := txPool.GetTransactions()
73         txEntries := make([]*bc.Tx, 0, len(txDescs))
74         blockWeight := uint64(0)
75         txFee := uint64(0)
76
77         var compareDiffBH *legacy.BlockHeader
78         if compareDiffBlock, err := c.GetBlockByHeight(nextBlockHeight - consensus.BlocksPerRetarget); err == nil {
79                 compareDiffBH = &compareDiffBlock.BlockHeader
80         }
81
82         b := &legacy.Block{
83                 BlockHeader: legacy.BlockHeader{
84                         Version:           1,
85                         Height:            nextBlockHeight,
86                         PreviousBlockHash: preBlock.Hash(),
87                         Seed:              *nextBlockSeed,
88                         TimestampMS:       bc.Millis(time.Now()),
89                         BlockCommitment:   legacy.BlockCommitment{},
90                         Bits:              difficulty.CalcNextRequiredDifficulty(&preBlock.BlockHeader, compareDiffBH),
91                 },
92                 Transactions: make([]*legacy.Tx, 0, len(txDescs)),
93         }
94
95         appendTx := func(tx *legacy.Tx, weight, fee uint64) {
96                 b.Transactions = append([]*legacy.Tx{tx}, b.Transactions...)
97                 txEntries = append([]*bc.Tx{tx.Tx}, txEntries...)
98                 blockWeight += weight
99                 txFee += fee
100         }
101
102         bcBlock := legacy.MapBlock(b)
103         for _, txDesc := range txDescs {
104                 tx := txDesc.Tx.Tx
105                 if blockWeight+txDesc.Weight > consensus.MaxBlockSzie-consensus.MaxTxSize {
106                         break
107                 }
108                 if err := c.GetTransactionsUtxo(view, []*bc.Tx{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 := view.ApplyTransaction(bcBlock, tx); err != nil {
114                         log.WithField("error", err).Error("mining block generate skip tx due to")
115                         txPool.RemoveTransaction(&tx.ID)
116                         continue
117                 }
118                 if _, err := validation.ValidateTx(tx, preBcBlock); err != nil {
119                         log.WithField("error", err).Error("mining block generate skip tx due to")
120                         txPool.RemoveTransaction(&tx.ID)
121                         continue
122                 }
123
124                 appendTx(txDesc.Tx, txDesc.Weight, txDesc.Fee)
125         }
126
127         cbTx, err := createCoinbaseTx(accountManager, txFee, nextBlockHeight)
128         if err != nil {
129                 return nil, errors.Wrap(err, "fail on createCoinbaseTx")
130         }
131         appendTx(cbTx, 0, 0)
132
133         b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.MerkleRoot(txEntries)
134         if err != nil {
135                 return nil, errors.Wrap(err, "calculating tx merkle root")
136         }
137
138         return b, nil
139 }