OSDN Git Service

Merge branch 'dev' into dev-verify
[bytom/bytom.git] / mining / mining.go
index ecf0a3f..e85326e 100644 (file)
 package mining
 
 import (
-       "fmt"
+       "sort"
        "time"
 
+       log "github.com/sirupsen/logrus"
+
+       "github.com/bytom/account"
        "github.com/bytom/blockchain/txbuilder"
        "github.com/bytom/consensus"
        "github.com/bytom/errors"
        "github.com/bytom/protocol"
        "github.com/bytom/protocol/bc"
-       "github.com/bytom/protocol/bc/legacy"
+       "github.com/bytom/protocol/bc/types"
        "github.com/bytom/protocol/state"
        "github.com/bytom/protocol/validation"
-       "github.com/bytom/protocol/vm"
        "github.com/bytom/protocol/vm/vmutil"
 )
 
-// standardCoinbaseScript returns a standard script suitable for use as the
-// signature script of the coinbase transaction of a new block.
-func standardCoinbaseScript(blockHeight uint64) ([]byte, error) {
-       //TODO: add verify conditions, block heigh & sign
-       scriptBuild := vmutil.NewBuilder()
-       scriptBuild.AddOp(vm.OP_TRUE)
-       return scriptBuild.Build()
-}
-
 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
 // based on the passed block height to the provided address.  When the address
 // is nil, the coinbase transaction will instead be redeemable by anyone.
-func createCoinbaseTx(amount uint64, blockHeight uint64, addr []byte) (*legacy.Tx, error) {
-       //TODO: make sure things works
+func createCoinbaseTx(accountManager *account.Manager, amount uint64, blockHeight uint64) (tx *types.Tx, err error) {
        amount += consensus.BlockSubsidy(blockHeight)
-       cbScript, err := standardCoinbaseScript(blockHeight)
+
+       var script []byte
+       if accountManager == nil {
+               script, err = vmutil.DefaultCoinbaseProgram()
+       } else {
+               script, err = accountManager.GetCoinbaseControlProgram()
+       }
        if err != nil {
-               return nil, err
+               return
        }
 
        builder := txbuilder.NewBuilder(time.Now())
-       builder.AddOutput(legacy.NewTxOutput(*consensus.BTMAssetID, amount, cbScript, nil))
+       if err = builder.AddInput(types.NewCoinbaseInput([]byte(string(blockHeight))), &txbuilder.SigningInstruction{}); err != nil {
+               return
+       }
+       if err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {
+               return
+       }
        _, txData, err := builder.Build()
-       tx := &legacy.Tx{
+       if err != nil {
+               return
+       }
+
+       byteData, err := txData.MarshalText()
+       if err != nil {
+               return
+       }
+       txData.SerializedSize = uint64(len(byteData))
+
+       tx = &types.Tx{
                TxData: *txData,
-               Tx:     legacy.MapTx(txData),
+               Tx:     types.MapTx(txData),
        }
-       return tx, err
+       return
 }
 
 // NewBlockTemplate returns a new block template that is ready to be solved
-func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, addr []byte) (*legacy.Block, error) {
-       // Extend the most recently known best block.
-       var err error
-       preBlock, snap := c.State()
-       newSnap := state.Copy(snap)
-
-       nextBlockHeight := preBlock.BlockHeader.Height + 1
-       preBcBlock := legacy.MapBlock(preBlock)
-       txDescs := txPool.GetTransactions()
-       txEntries := make([]*bc.Tx, 0, len(txDescs))
-       blockWeight := uint64(0)
+func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) (b *types.Block, err error) {
+       view := state.NewUtxoViewpoint()
+       txStatus := bc.NewTransactionStatus()
+       txStatus.SetStatus(0, false)
+       txEntries := []*bc.Tx{nil}
+       gasUsed := uint64(0)
        txFee := uint64(0)
 
-       var compareDiffBH *legacy.BlockHeader
-       if compareDiffBlock, err := c.GetBlock(nextBlockHeight - consensus.BlocksPerRetarget); err == nil {
-               compareDiffBH = &compareDiffBlock.BlockHeader
+       // get preblock info for generate next block
+       preBlockHeader := c.BestBlockHeader()
+       preBlockHash := preBlockHeader.Hash()
+       nextBlockHeight := preBlockHeader.Height + 1
+       nextBits, err := c.CalcNextBits(&preBlockHash)
+       if err != nil {
+               return nil, err
        }
 
-       b := &legacy.Block{
-               BlockHeader: legacy.BlockHeader{
+       b = &types.Block{
+               BlockHeader: types.BlockHeader{
                        Version:           1,
                        Height:            nextBlockHeight,
-                       PreviousBlockHash: preBlock.Hash(),
-                       TimestampMS:       bc.Millis(time.Now()),
-                       BlockCommitment:   legacy.BlockCommitment{},
-                       Bits:              consensus.CalcNextRequiredDifficulty(&preBlock.BlockHeader, compareDiffBH),
+                       PreviousBlockHash: preBlockHash,
+                       Timestamp:         uint64(time.Now().Unix()),
+                       BlockCommitment:   types.BlockCommitment{},
+                       Bits:              nextBits,
                },
-               Transactions: make([]*legacy.Tx, 0, len(txDescs)),
        }
-       newSnap.PruneNonces(b.BlockHeader.TimestampMS)
+       bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
+       b.Transactions = []*types.Tx{nil}
 
-       appendTx := func(tx *legacy.Tx, weight, fee uint64) {
-               b.Transactions = append([]*legacy.Tx{tx}, b.Transactions...)
-               txEntries = append([]*bc.Tx{tx.Tx}, txEntries...)
-               blockWeight += weight
-               txFee += fee
-       }
-
-       for _, txDesc := range txDescs {
+       txs := txPool.GetTransactions()
+       sort.Sort(ByTime(txs))
+       for _, txDesc := range txs {
                tx := txDesc.Tx.Tx
-               if blockWeight+txDesc.Weight > consensus.MaxBlockSzie-consensus.MaxTxSize {
-                       break
-               }
-               if err := newSnap.ApplyTx(tx); err != nil {
-                       fmt.Println("mining block generate skip tx due to %v", err)
+               gasOnlyTx := false
+
+               if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
+                       log.WithField("error", err).Error("mining block generate skip tx due to")
                        txPool.RemoveTransaction(&tx.ID)
                        continue
                }
-               if _, err := validation.ValidateTx(tx, preBcBlock); err != nil {
-                       fmt.Println("mining block generate skip tx due to %v", err)
+
+               gasStatus, err := validation.ValidateTx(tx, bcBlock)
+               if err != nil {
+                       if !gasStatus.GasValid {
+                               log.WithField("error", err).Error("mining block generate skip tx due to")
+                               txPool.RemoveTransaction(&tx.ID)
+                               continue
+                       }
+                       gasOnlyTx = true
+               }
+
+               if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
+                       break
+               }
+
+               if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
+                       log.WithField("error", err).Error("mining block generate skip tx due to")
                        txPool.RemoveTransaction(&tx.ID)
                        continue
                }
 
-               appendTx(txDesc.Tx, txDesc.Weight, txDesc.Fee)
+               txStatus.SetStatus(len(b.Transactions), gasOnlyTx)
+               b.Transactions = append(b.Transactions, txDesc.Tx)
+               txEntries = append(txEntries, tx)
+               gasUsed += uint64(gasStatus.GasUsed)
+               txFee += txDesc.Fee
+
+               if gasUsed == consensus.MaxBlockGas {
+                       break
+               }
        }
 
-       cbTx, _ := createCoinbaseTx(txFee, nextBlockHeight, addr)
-       if err := newSnap.ApplyTx(cbTx.Tx); err != nil {
-               return nil, errors.Wrap(err, "fail on append coinbase transaction to snap")
+       // creater coinbase transaction
+       b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
+       if err != nil {
+               return nil, errors.Wrap(err, "fail on createCoinbaseTx")
        }
-       appendTx(cbTx, 0, 0)
+       txEntries[0] = b.Transactions[0].Tx
 
-       b.BlockHeader.BlockCommitment.AssetsMerkleRoot = newSnap.Tree.RootHash()
-       b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.MerkleRoot(txEntries)
+       b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.TxMerkleRoot(txEntries)
        if err != nil {
-               return nil, errors.Wrap(err, "calculating tx merkle root")
+               return nil, err
        }
 
-       return b, nil
+       b.BlockHeader.BlockCommitment.TransactionStatusHash, err = bc.TxStatusMerkleRoot(txStatus.VerifyStatus)
+       return b, err
 }