-// Copyright (c) 2014-2016 The btcsuite developers
-// Use of this source code is governed by an ISC
-// license that can be found in the LICENSE file.
-
package mining
import (
+ "sort"
+ "strconv"
"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)
+ arbitrary := append([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...)
+
+ var script []byte
+ if accountManager == nil {
+ script, err = vmutil.DefaultCoinbaseProgram()
+ } else {
+ script, err = accountManager.GetCoinbaseControlProgram()
+ arbitrary = append(arbitrary, accountManager.GetCoinbaseArbitrary()...)
+ }
if err != nil {
return nil, err
}
+ if len(arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
+ return nil, validation.ErrCoinbaseArbitraryOversize
+ }
+
builder := txbuilder.NewBuilder(time.Now())
- builder.AddOutput(legacy.NewTxOutput(*consensus.BTMAssetID, amount, cbScript, nil))
+ if err = builder.AddInput(types.NewCoinbaseInput(arbitrary), &txbuilder.SigningInstruction{}); err != nil {
+ return nil, err
+ }
+ if err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {
+ return nil, err
+ }
_, txData, err := builder.Build()
- tx := &legacy.Tx{
+ if err != nil {
+ return nil, err
+ }
+
+ byteData, err := txData.MarshalText()
+ if err != nil {
+ return nil, err
+ }
+ txData.SerializedSize = uint64(len(byteData))
+
+ tx = &types.Tx{
TxData: *txData,
- Tx: legacy.MapTx(txData),
+ Tx: types.MapTx(txData),
}
- return tx, err
+ return tx, nil
}
// 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
- newSnap := state.Empty()
- var blockData *bc.Block
- nextBlockHeight := uint64(1)
- preBlockHash := bc.Hash{}
-
- block, snap := c.State()
- if block != nil {
- nextBlockHeight = block.BlockHeader.Height + 1
- preBlockHash = block.Hash()
- newSnap = state.Copy(snap)
- blockData = legacy.MapBlock(block)
+func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) (b *types.Block, err error) {
+ view := state.NewUtxoViewpoint()
+ txStatus := bc.NewTransactionStatus()
+ if err := txStatus.SetStatus(0, false); err != nil {
+ return nil, err
}
-
- txDescs := txPool.GetTransactions()
- blockTxns := make([]*legacy.Tx, 0, len(txDescs))
- blockWeight := uint64(0)
+ txEntries := []*bc.Tx{nil}
+ gasUsed := uint64(0)
txFee := uint64(0)
- b := &legacy.Block{
- BlockHeader: legacy.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 = &types.Block{
+ BlockHeader: types.BlockHeader{
Version: 1,
Height: nextBlockHeight,
PreviousBlockHash: preBlockHash,
- TimestampMS: bc.Millis(time.Now()),
- BlockCommitment: legacy.BlockCommitment{},
- Bits: consensus.CalcNextRequiredDifficulty(),
+ Timestamp: uint64(time.Now().Unix()),
+ BlockCommitment: types.BlockCommitment{},
+ Bits: nextBits,
},
}
- newSnap.PruneNonces(b.BlockHeader.TimestampMS)
+ bcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}
+ b.Transactions = []*types.Tx{nil}
- var txEntries []*bc.Tx
- for _, txDesc := range txDescs {
+ txs := txPool.GetTransactions()
+ sort.Sort(byTime(txs))
+ for _, txDesc := range txs {
tx := txDesc.Tx.Tx
- blockPlusTxWeight := blockWeight + txDesc.Weight
- if blockPlusTxWeight > consensus.MaxBlockSzie {
+ gasOnlyTx := false
+
+ if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {
+ blkGenSkipTxForErr(txPool, &tx.ID, err)
+ continue
+ }
+
+ gasStatus, err := validation.ValidateTx(tx, bcBlock)
+ if err != nil {
+ if !gasStatus.GasValid {
+ blkGenSkipTxForErr(txPool, &tx.ID, err)
+ continue
+ }
+ gasOnlyTx = true
+ }
+
+ if gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {
break
}
- if err := newSnap.ApplyTx(tx); err != nil {
- txPool.RemoveTransaction(&tx.ID)
+ if err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {
+ blkGenSkipTxForErr(txPool, &tx.ID, err)
continue
}
- if _, err := validation.ValidateTx(tx, blockData); err != nil {
- txPool.RemoveTransaction(&tx.ID)
- continue
+ if err := txStatus.SetStatus(len(b.Transactions), gasOnlyTx); err != nil {
+ return nil, err
}
- blockTxns = append(blockTxns, txDesc.Tx)
+ b.Transactions = append(b.Transactions, txDesc.Tx)
txEntries = append(txEntries, tx)
- blockWeight = blockPlusTxWeight
+ gasUsed += uint64(gasStatus.GasUsed)
txFee += txDesc.Fee
- }
- cbTx, _ := createCoinbaseTx(txFee, nextBlockHeight, addr)
- newSnap.ApplyTx(cbTx.Tx)
- blockTxns = append([]*legacy.Tx{cbTx}, blockTxns...)
+ if gasUsed == consensus.MaxBlockGas {
+ break
+ }
+ }
- b.Transactions = blockTxns
+ // creater coinbase transaction
+ b.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)
+ if err != nil {
+ return nil, errors.Wrap(err, "fail on createCoinbaseTx")
+ }
+ txEntries[0] = b.Transactions[0].Tx
- b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.MerkleRoot(txEntries)
- b.BlockHeader.BlockCommitment.AssetsMerkleRoot = newSnap.Tree.RootHash()
+ b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = types.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 = types.TxStatusMerkleRoot(txStatus.VerifyStatus)
+ return b, err
+}
+
+func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
+ log.WithField("error", err).Error("mining block generation: skip tx due to")
+ txPool.RemoveTransaction(txHash)
}