Update btcchain import paths to new location.

This commit is contained in:
Dave Collins 2015-01-30 16:25:42 -06:00
parent 74ae61f048
commit 624bbb3216
13 changed files with 163 additions and 162 deletions

View file

@ -13,7 +13,7 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/btcsuite/btcchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
@ -114,7 +114,7 @@ type processBlockResponse struct {
// way to call ProcessBlock on the internal block chain instance. // way to call ProcessBlock on the internal block chain instance.
type processBlockMsg struct { type processBlockMsg struct {
block *btcutil.Block block *btcutil.Block
flags btcchain.BehaviorFlags flags blockchain.BehaviorFlags
reply chan processBlockResponse reply chan processBlockResponse
} }
@ -163,7 +163,7 @@ type blockManager struct {
server *server server *server
started int32 started int32
shutdown int32 shutdown int32
blockChain *btcchain.BlockChain blockChain *blockchain.BlockChain
requestedTxns map[btcwire.ShaHash]struct{} requestedTxns map[btcwire.ShaHash]struct{}
requestedBlocks map[btcwire.ShaHash]struct{} requestedBlocks map[btcwire.ShaHash]struct{}
receivedLogBlocks int64 receivedLogBlocks int64
@ -567,13 +567,13 @@ func (b *blockManager) handleBlockMsg(bmsg *blockMsg) {
// since it is needed to verify the next round of headers links // since it is needed to verify the next round of headers links
// properly. // properly.
isCheckpointBlock := false isCheckpointBlock := false
behaviorFlags := btcchain.BFNone behaviorFlags := blockchain.BFNone
if b.headersFirstMode { if b.headersFirstMode {
firstNodeEl := b.headerList.Front() firstNodeEl := b.headerList.Front()
if firstNodeEl != nil { if firstNodeEl != nil {
firstNode := firstNodeEl.Value.(*headerNode) firstNode := firstNodeEl.Value.(*headerNode)
if blockSha.IsEqual(firstNode.sha) { if blockSha.IsEqual(firstNode.sha) {
behaviorFlags |= btcchain.BFFastAdd behaviorFlags |= blockchain.BFFastAdd
if firstNode.sha.IsEqual(b.nextCheckpoint.Hash) { if firstNode.sha.IsEqual(b.nextCheckpoint.Hash) {
isCheckpointBlock = true isCheckpointBlock = true
} else { } else {
@ -598,7 +598,7 @@ func (b *blockManager) handleBlockMsg(bmsg *blockMsg) {
// rejected as opposed to something actually going wrong, so log // rejected as opposed to something actually going wrong, so log
// it as such. Otherwise, something really did go wrong, so log // it as such. Otherwise, something really did go wrong, so log
// it as an actual error. // it as an actual error.
if _, ok := err.(btcchain.RuleError); ok { if _, ok := err.(blockchain.RuleError); ok {
bmgrLog.Infof("Rejected block %v from %s: %v", blockSha, bmgrLog.Infof("Rejected block %v from %s: %v", blockSha,
bmsg.peer, err) bmsg.peer, err)
} else { } else {
@ -672,7 +672,7 @@ func (b *blockManager) handleBlockMsg(bmsg *blockMsg) {
prevHash := b.nextCheckpoint.Hash prevHash := b.nextCheckpoint.Hash
b.nextCheckpoint = b.findNextHeaderCheckpoint(prevHeight) b.nextCheckpoint = b.findNextHeaderCheckpoint(prevHeight)
if b.nextCheckpoint != nil { if b.nextCheckpoint != nil {
locator := btcchain.BlockLocator([]*btcwire.ShaHash{prevHash}) locator := blockchain.BlockLocator([]*btcwire.ShaHash{prevHash})
err := bmsg.peer.PushGetHeadersMsg(locator, b.nextCheckpoint.Hash) err := bmsg.peer.PushGetHeadersMsg(locator, b.nextCheckpoint.Hash)
if err != nil { if err != nil {
bmgrLog.Warnf("Failed to send getheaders message to "+ bmgrLog.Warnf("Failed to send getheaders message to "+
@ -691,7 +691,7 @@ func (b *blockManager) handleBlockMsg(bmsg *blockMsg) {
b.headersFirstMode = false b.headersFirstMode = false
b.headerList.Init() b.headerList.Init()
bmgrLog.Infof("Reached the final checkpoint -- switching to normal mode") bmgrLog.Infof("Reached the final checkpoint -- switching to normal mode")
locator := btcchain.BlockLocator([]*btcwire.ShaHash{blockSha}) locator := blockchain.BlockLocator([]*btcwire.ShaHash{blockSha})
err = bmsg.peer.PushGetBlocksMsg(locator, &zeroHash) err = bmsg.peer.PushGetBlocksMsg(locator, &zeroHash)
if err != nil { if err != nil {
bmgrLog.Warnf("Failed to send getblocks message to peer %s: %v", bmgrLog.Warnf("Failed to send getblocks message to peer %s: %v",
@ -842,7 +842,7 @@ func (b *blockManager) handleHeadersMsg(hmsg *headersMsg) {
// This header is not a checkpoint, so request the next batch of // This header is not a checkpoint, so request the next batch of
// headers starting from the latest known header and ending with the // headers starting from the latest known header and ending with the
// next checkpoint. // next checkpoint.
locator := btcchain.BlockLocator([]*btcwire.ShaHash{finalHash}) locator := blockchain.BlockLocator([]*btcwire.ShaHash{finalHash})
err := hmsg.peer.PushGetHeadersMsg(locator, b.nextCheckpoint.Hash) err := hmsg.peer.PushGetHeadersMsg(locator, b.nextCheckpoint.Hash)
if err != nil { if err != nil {
bmgrLog.Warnf("Failed to send getheaders message to "+ bmgrLog.Warnf("Failed to send getheaders message to "+
@ -1105,13 +1105,13 @@ out:
bmgrLog.Trace("Block handler done") bmgrLog.Trace("Block handler done")
} }
// handleNotifyMsg handles notifications from btcchain. It does things such // handleNotifyMsg handles notifications from blockchain. It does things such
// as request orphan block parents and relay accepted blocks to connected peers. // as request orphan block parents and relay accepted blocks to connected peers.
func (b *blockManager) handleNotifyMsg(notification *btcchain.Notification) { func (b *blockManager) handleNotifyMsg(notification *blockchain.Notification) {
switch notification.Type { switch notification.Type {
// A block has been accepted into the block chain. Relay it to other // A block has been accepted into the block chain. Relay it to other
// peers. // peers.
case btcchain.NTBlockAccepted: case blockchain.NTBlockAccepted:
// Don't relay if we are not current. Other peers that are // Don't relay if we are not current. Other peers that are
// current should already know about it. // current should already know about it.
@ -1134,7 +1134,7 @@ func (b *blockManager) handleNotifyMsg(notification *btcchain.Notification) {
b.server.RelayInventory(iv, nil) b.server.RelayInventory(iv, nil)
// A block has been connected to the main block chain. // A block has been connected to the main block chain.
case btcchain.NTBlockConnected: case blockchain.NTBlockConnected:
block, ok := notification.Data.(*btcutil.Block) block, ok := notification.Data.(*btcutil.Block)
if !ok { if !ok {
bmgrLog.Warnf("Chain connected notification is not a block.") bmgrLog.Warnf("Chain connected notification is not a block.")
@ -1168,7 +1168,7 @@ func (b *blockManager) handleNotifyMsg(notification *btcchain.Notification) {
} }
// A block has been disconnected from the main block chain. // A block has been disconnected from the main block chain.
case btcchain.NTBlockDisconnected: case blockchain.NTBlockDisconnected:
block, ok := notification.Data.(*btcutil.Block) block, ok := notification.Data.(*btcutil.Block)
if !ok { if !ok {
bmgrLog.Warnf("Chain disconnected notification is not a block.") bmgrLog.Warnf("Chain disconnected notification is not a block.")
@ -1320,7 +1320,7 @@ func (b *blockManager) CalcNextRequiredDifficulty(timestamp time.Time) (uint32,
// ProcessBlock makes use of ProcessBlock on an internal instance of a block // ProcessBlock makes use of ProcessBlock on an internal instance of a block
// chain. It is funneled through the block manager since btcchain is not safe // chain. It is funneled through the block manager since btcchain is not safe
// for concurrent access. // for concurrent access.
func (b *blockManager) ProcessBlock(block *btcutil.Block, flags btcchain.BehaviorFlags) (bool, error) { func (b *blockManager) ProcessBlock(block *btcutil.Block, flags blockchain.BehaviorFlags) (bool, error) {
reply := make(chan processBlockResponse, 1) reply := make(chan processBlockResponse, 1)
b.msgChan <- processBlockMsg{block: block, flags: flags, reply: reply} b.msgChan <- processBlockMsg{block: block, flags: flags, reply: reply}
response := <-reply response := <-reply
@ -1352,7 +1352,7 @@ func newBlockManager(s *server) (*blockManager, error) {
headerList: list.New(), headerList: list.New(),
quit: make(chan struct{}), quit: make(chan struct{}),
} }
bm.blockChain = btcchain.New(s.db, s.netParams, bm.handleNotifyMsg) bm.blockChain = blockchain.New(s.db, s.netParams, bm.handleNotifyMsg)
bm.blockChain.DisableCheckpoints(cfg.DisableCheckpoints) bm.blockChain.DisableCheckpoints(cfg.DisableCheckpoints)
if !cfg.DisableCheckpoints { if !cfg.DisableCheckpoints {
// Initialize the next checkpoint based on the current height. // Initialize the next checkpoint based on the current height.

View file

@ -9,7 +9,7 @@ import (
"path/filepath" "path/filepath"
"runtime" "runtime"
"github.com/btcsuite/btcchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
"github.com/btcsuite/btcd/limits" "github.com/btcsuite/btcd/limits"
@ -81,7 +81,7 @@ func realMain() error {
defer backendLogger.Flush() defer backendLogger.Flush()
log = btclog.NewSubsystemLogger(backendLogger, "") log = btclog.NewSubsystemLogger(backendLogger, "")
database.UseLogger(btclog.NewSubsystemLogger(backendLogger, "BCDB: ")) database.UseLogger(btclog.NewSubsystemLogger(backendLogger, "BCDB: "))
btcchain.UseLogger(btclog.NewSubsystemLogger(backendLogger, "CHAN: ")) blockchain.UseLogger(btclog.NewSubsystemLogger(backendLogger, "CHAN: "))
// Load the block database. // Load the block database.
db, err := loadBlockDB() db, err := loadBlockDB()

View file

@ -11,7 +11,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/btcsuite/btcchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
@ -31,8 +31,8 @@ type importResults struct {
// file to the block database. // file to the block database.
type blockImporter struct { type blockImporter struct {
db database.Db db database.Db
chain *btcchain.BlockChain chain *blockchain.BlockChain
medianTime btcchain.MedianTimeSource medianTime blockchain.MedianTimeSource
r io.ReadSeeker r io.ReadSeeker
processQueue chan []byte processQueue chan []byte
doneChan chan bool doneChan chan bool
@ -134,7 +134,7 @@ func (bi *blockImporter) processBlock(serializedBlock []byte) (bool, error) {
// Ensure the blocks follows all of the chain rules and match up to the // Ensure the blocks follows all of the chain rules and match up to the
// known checkpoints. // known checkpoints.
isOrphan, err := bi.chain.ProcessBlock(block, bi.medianTime, isOrphan, err := bi.chain.ProcessBlock(block, bi.medianTime,
btcchain.BFFastAdd) blockchain.BFFastAdd)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -307,8 +307,8 @@ func newBlockImporter(db database.Db, r io.ReadSeeker) *blockImporter {
doneChan: make(chan bool), doneChan: make(chan bool),
errChan: make(chan error), errChan: make(chan error),
quit: make(chan struct{}), quit: make(chan struct{}),
chain: btcchain.New(db, activeNetParams, nil), chain: blockchain.New(db, activeNetParams, nil),
medianTime: btcchain.NewMedianTime(), medianTime: blockchain.NewMedianTime(),
lastLogTime: time.Now(), lastLogTime: time.Now(),
} }
} }

View file

@ -9,7 +9,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"github.com/btcsuite/btcchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
_ "github.com/btcsuite/btcd/database/ldb" _ "github.com/btcsuite/btcd/database/ldb"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
@ -53,7 +53,7 @@ func findCandidates(db database.Db, latestHash *btcwire.ShaHash) ([]*btcnet.Chec
// Setup chain and get the latest checkpoint. Ignore notifications // Setup chain and get the latest checkpoint. Ignore notifications
// since they aren't needed for this util. // since they aren't needed for this util.
chain := btcchain.New(db, activeNetParams, nil) chain := blockchain.New(db, activeNetParams, nil)
latestCheckpoint := chain.LatestCheckpoint() latestCheckpoint := chain.LatestCheckpoint()
if latestCheckpoint == nil { if latestCheckpoint == nil {
return nil, fmt.Errorf("unable to retrieve latest checkpoint") return nil, fmt.Errorf("unable to retrieve latest checkpoint")
@ -61,7 +61,7 @@ func findCandidates(db database.Db, latestHash *btcwire.ShaHash) ([]*btcnet.Chec
// The latest known block must be at least the last known checkpoint // The latest known block must be at least the last known checkpoint
// plus required checkpoint confirmations. // plus required checkpoint confirmations.
checkpointConfirmations := int64(btcchain.CheckpointConfirmations) checkpointConfirmations := int64(blockchain.CheckpointConfirmations)
requiredHeight := latestCheckpoint.Height + checkpointConfirmations requiredHeight := latestCheckpoint.Height + checkpointConfirmations
if block.Height() < requiredHeight { if block.Height() < requiredHeight {
return nil, fmt.Errorf("the block database is only at height "+ return nil, fmt.Errorf("the block database is only at height "+

View file

@ -11,7 +11,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/btcsuite/btcchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcwire"
) )
@ -129,11 +129,11 @@ func (m *CPUMiner) submitBlock(block *btcutil.Block) bool {
// Process this block using the same rules as blocks coming from other // Process this block using the same rules as blocks coming from other
// nodes. This will in turn relay it to the network like normal. // nodes. This will in turn relay it to the network like normal.
isOrphan, err := m.server.blockManager.ProcessBlock(block, btcchain.BFNone) isOrphan, err := m.server.blockManager.ProcessBlock(block, blockchain.BFNone)
if err != nil { if err != nil {
// Anything other than a rule violation is an unexpected error, // Anything other than a rule violation is an unexpected error,
// so log that error as an internal error. // so log that error as an internal error.
if _, ok := err.(btcchain.RuleError); !ok { if _, ok := err.(blockchain.RuleError); !ok {
minrLog.Errorf("Unexpected error while processing "+ minrLog.Errorf("Unexpected error while processing "+
"block submitted via CPU miner: %v", err) "block submitted via CPU miner: %v", err)
return false return false
@ -178,7 +178,7 @@ func (m *CPUMiner) solveBlock(msgBlock *btcwire.MsgBlock, blockHeight int64,
// Create a couple of convenience variables. // Create a couple of convenience variables.
header := &msgBlock.Header header := &msgBlock.Header
targetDifficulty := btcchain.CompactToBig(header.Bits) targetDifficulty := blockchain.CompactToBig(header.Bits)
// Initial state. // Initial state.
lastGenerated := time.Now() lastGenerated := time.Now()
@ -239,7 +239,7 @@ func (m *CPUMiner) solveBlock(msgBlock *btcwire.MsgBlock, blockHeight int64,
// The block is solved when the new block hash is less // The block is solved when the new block hash is less
// than the target difficulty. Yay! // than the target difficulty. Yay!
if btcchain.ShaHashToBig(&hash).Cmp(targetDifficulty) <= 0 { if blockchain.ShaHashToBig(&hash).Cmp(targetDifficulty) <= 0 {
m.updateHashes <- hashesCompleted m.updateHashes <- hashesCompleted
return true return true
} }

View file

@ -197,8 +197,8 @@ information.
[btcjson](https://github.com/btcsuite/btcjson)) [btcjson](https://github.com/btcsuite/btcjson))
* [btcwire](https://github.com/btcsuite/btcwire) - Implements the Bitcoin * [btcwire](https://github.com/btcsuite/btcwire) - Implements the Bitcoin
wire protocol wire protocol
* [btcchain](https://github.com/btcsuite/btcchain) - Implements Bitcoin * [blockchain](https://github.com/btcsuite/btcd/blockchain) - Implements
block handling and chain selection rules Bitcoin block handling and chain selection rules
* [txscript](https://github.com/btcsuite/btcd/txscript) - Implements the * [txscript](https://github.com/btcsuite/btcd/txscript) - Implements the
Bitcoin transaction scripting language Bitcoin transaction scripting language
* [btcec](https://github.com/btcsuite/btcec) - Implements support for the * [btcec](https://github.com/btcsuite/btcec) - Implements support for the

4
log.go
View file

@ -12,7 +12,7 @@ import (
"github.com/btcsuite/btcd/addrmgr" "github.com/btcsuite/btcd/addrmgr"
"github.com/btcsuite/btcchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btclog" "github.com/btcsuite/btclog"
@ -110,7 +110,7 @@ func useLogger(subsystemID string, logger btclog.Logger) {
case "CHAN": case "CHAN":
chanLog = logger chanLog = logger
btcchain.UseLogger(logger) blockchain.UseLogger(logger)
case "DISC": case "DISC":
discLog = logger discLog = logger

View file

@ -13,7 +13,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/btcsuite/btcchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
@ -39,7 +39,7 @@ const (
// maxSigOpsPerTx is the maximum number of signature operations // maxSigOpsPerTx is the maximum number of signature operations
// in a single transaction we will relay or mine. It is a fraction // in a single transaction we will relay or mine. It is a fraction
// of the max signature operations for a block. // of the max signature operations for a block.
maxSigOpsPerTx = btcchain.MaxSigOpsPerBlock / 5 maxSigOpsPerTx = blockchain.MaxSigOpsPerBlock / 5
// maxStandardTxSize is the maximum size allowed for transactions that // maxStandardTxSize is the maximum size allowed for transactions that
// are considered standard and will therefore be relayed and considered // are considered standard and will therefore be relayed and considered
@ -237,7 +237,7 @@ func checkTransactionStandard(tx *btcutil.Tx, height int64) error {
// The transaction must be finalized to be standard and therefore // The transaction must be finalized to be standard and therefore
// considered for inclusion in a block. // considered for inclusion in a block.
if !btcchain.IsFinalizedTransaction(tx, height, time.Now()) { if !blockchain.IsFinalizedTransaction(tx, height, time.Now()) {
return txRuleError(btcwire.RejectNonstandard, return txRuleError(btcwire.RejectNonstandard,
"transaction is not finalized") "transaction is not finalized")
} }
@ -332,7 +332,7 @@ func checkTransactionStandard(tx *btcutil.Tx, height int64) error {
// exhaustion attacks by "creative" use of scripts that are super expensive to // exhaustion attacks by "creative" use of scripts that are super expensive to
// process like OP_DUP OP_CHECKSIG OP_DROP repeated a large number of times // process like OP_DUP OP_CHECKSIG OP_DROP repeated a large number of times
// followed by a final OP_TRUE. // followed by a final OP_TRUE.
func checkInputsStandard(tx *btcutil.Tx, txStore btcchain.TxStore) error { func checkInputsStandard(tx *btcutil.Tx, txStore blockchain.TxStore) error {
// NOTE: The reference implementation also does a coinbase check here, // NOTE: The reference implementation also does a coinbase check here,
// but coinbases have already been rejected prior to calling this // but coinbases have already been rejected prior to calling this
// function so no need to recheck. // function so no need to recheck.
@ -463,7 +463,7 @@ func (mp *txMemPool) limitNumOrphans() error {
if foundHash == nil { if foundHash == nil {
foundHash = &txHash foundHash = &txHash
} }
txHashNum := btcchain.ShaHashToBig(&txHash) txHashNum := blockchain.ShaHashToBig(&txHash)
if txHashNum.Cmp(randHashNum) > 0 { if txHashNum.Cmp(randHashNum) > 0 {
foundHash = &txHash foundHash = &txHash
break break
@ -677,7 +677,7 @@ func (mp *txMemPool) addTransaction(tx *btcutil.Tx, height, fee int64) {
// age is the sum of this value for each txin. Any inputs to the transaction // age is the sum of this value for each txin. Any inputs to the transaction
// which are currently in the mempool and hence not mined into a block yet, // which are currently in the mempool and hence not mined into a block yet,
// contribute no additional input age to the transaction. // contribute no additional input age to the transaction.
func calcInputValueAge(txDesc *TxDesc, txStore btcchain.TxStore, nextBlockHeight int64) float64 { func calcInputValueAge(txDesc *TxDesc, txStore blockchain.TxStore, nextBlockHeight int64) float64 {
var totalInputAge float64 var totalInputAge float64
for _, txIn := range txDesc.Tx.MsgTx().TxIn { for _, txIn := range txDesc.Tx.MsgTx().TxIn {
originHash := &txIn.PreviousOutPoint.Hash originHash := &txIn.PreviousOutPoint.Hash
@ -710,7 +710,7 @@ func calcInputValueAge(txDesc *TxDesc, txStore btcchain.TxStore, nextBlockHeight
// StartingPriority calculates the priority of this tx descriptor's underlying // StartingPriority calculates the priority of this tx descriptor's underlying
// transaction relative to when it was first added to the mempool. The result // transaction relative to when it was first added to the mempool. The result
// is lazily computed and then cached for subsequent function calls. // is lazily computed and then cached for subsequent function calls.
func (txD *TxDesc) StartingPriority(txStore btcchain.TxStore) float64 { func (txD *TxDesc) StartingPriority(txStore blockchain.TxStore) float64 {
// Return our cached result. // Return our cached result.
if txD.startingPriority != float64(0) { if txD.startingPriority != float64(0) {
return txD.startingPriority return txD.startingPriority
@ -726,7 +726,7 @@ func (txD *TxDesc) StartingPriority(txStore btcchain.TxStore) float64 {
// CurrentPriority calculates the current priority of this tx descriptor's // CurrentPriority calculates the current priority of this tx descriptor's
// underlying transaction relative to the next block height. // underlying transaction relative to the next block height.
func (txD *TxDesc) CurrentPriority(txStore btcchain.TxStore, nextBlockHeight int64) float64 { func (txD *TxDesc) CurrentPriority(txStore blockchain.TxStore, nextBlockHeight int64) float64 {
inputAge := calcInputValueAge(txD, txStore, nextBlockHeight) inputAge := calcInputValueAge(txD, txStore, nextBlockHeight)
txSize := txD.Tx.MsgTx().SerializeSize() txSize := txD.Tx.MsgTx().SerializeSize()
return calcPriority(txD.Tx, txSize, inputAge) return calcPriority(txD.Tx, txSize, inputAge)
@ -756,7 +756,7 @@ func (mp *txMemPool) checkPoolDoubleSpend(tx *btcutil.Tx) error {
// fetch any missing inputs from the transaction pool. // fetch any missing inputs from the transaction pool.
// //
// This function MUST be called with the mempool lock held (for reads). // This function MUST be called with the mempool lock held (for reads).
func (mp *txMemPool) fetchInputTransactions(tx *btcutil.Tx) (btcchain.TxStore, error) { func (mp *txMemPool) fetchInputTransactions(tx *btcutil.Tx) (blockchain.TxStore, error) {
txStore, err := mp.server.blockManager.blockChain.FetchTransactionStore(tx) txStore, err := mp.server.blockManager.blockChain.FetchTransactionStore(tx)
if err != nil { if err != nil {
return nil, err return nil, err
@ -814,16 +814,16 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// Perform preliminary sanity checks on the transaction. This makes // Perform preliminary sanity checks on the transaction. This makes
// use of btcchain which contains the invariant rules for what // use of btcchain which contains the invariant rules for what
// transactions are allowed into blocks. // transactions are allowed into blocks.
err := btcchain.CheckTransactionSanity(tx) err := blockchain.CheckTransactionSanity(tx)
if err != nil { if err != nil {
if cerr, ok := err.(btcchain.RuleError); ok { if cerr, ok := err.(blockchain.RuleError); ok {
return nil, chainRuleError(cerr) return nil, chainRuleError(cerr)
} }
return nil, err return nil, err
} }
// A standalone transaction must not be a coinbase transaction. // A standalone transaction must not be a coinbase transaction.
if btcchain.IsCoinBase(tx) { if blockchain.IsCoinBase(tx) {
str := fmt.Sprintf("transaction %v is an individual coinbase", str := fmt.Sprintf("transaction %v is an individual coinbase",
txHash) txHash)
return nil, txRuleError(btcwire.RejectInvalid, str) return nil, txRuleError(btcwire.RejectInvalid, str)
@ -887,7 +887,7 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// needing to do a separate lookup. // needing to do a separate lookup.
txStore, err := mp.fetchInputTransactions(tx) txStore, err := mp.fetchInputTransactions(tx)
if err != nil { if err != nil {
if cerr, ok := err.(btcchain.RuleError); ok { if cerr, ok := err.(blockchain.RuleError); ok {
return nil, chainRuleError(cerr) return nil, chainRuleError(cerr)
} }
return nil, err return nil, err
@ -923,9 +923,9 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// rules in btcchain for what transactions are allowed into blocks. // rules in btcchain for what transactions are allowed into blocks.
// Also returns the fees associated with the transaction which will be // Also returns the fees associated with the transaction which will be
// used later. // used later.
txFee, err := btcchain.CheckTransactionInputs(tx, nextBlockHeight, txStore) txFee, err := blockchain.CheckTransactionInputs(tx, nextBlockHeight, txStore)
if err != nil { if err != nil {
if cerr, ok := err.(btcchain.RuleError); ok { if cerr, ok := err.(blockchain.RuleError); ok {
return nil, chainRuleError(cerr) return nil, chainRuleError(cerr)
} }
return nil, err return nil, err
@ -958,14 +958,14 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// the coinbase address itself can contain signature operations, the // the coinbase address itself can contain signature operations, the
// maximum allowed signature operations per transaction is less than // maximum allowed signature operations per transaction is less than
// the maximum allowed signature operations per block. // the maximum allowed signature operations per block.
numSigOps, err := btcchain.CountP2SHSigOps(tx, false, txStore) numSigOps, err := blockchain.CountP2SHSigOps(tx, false, txStore)
if err != nil { if err != nil {
if cerr, ok := err.(btcchain.RuleError); ok { if cerr, ok := err.(blockchain.RuleError); ok {
return nil, chainRuleError(cerr) return nil, chainRuleError(cerr)
} }
return nil, err return nil, err
} }
numSigOps += btcchain.CountSigOps(tx) numSigOps += blockchain.CountSigOps(tx)
if numSigOps > maxSigOpsPerTx { if numSigOps > maxSigOpsPerTx {
str := fmt.Sprintf("transaction %v has too many sigops: %d > %d", str := fmt.Sprintf("transaction %v has too many sigops: %d > %d",
txHash, numSigOps, maxSigOpsPerTx) txHash, numSigOps, maxSigOpsPerTx)
@ -1018,10 +1018,10 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit boo
// Verify crypto signatures for each input and reject the transaction if // Verify crypto signatures for each input and reject the transaction if
// any don't verify. // any don't verify.
err = btcchain.ValidateTransactionScripts(tx, txStore, err = blockchain.ValidateTransactionScripts(tx, txStore,
standardScriptVerifyFlags) standardScriptVerifyFlags)
if err != nil { if err != nil {
if cerr, ok := err.(btcchain.RuleError); ok { if cerr, ok := err.(blockchain.RuleError); ok {
return nil, chainRuleError(cerr) return nil, chainRuleError(cerr)
} }
return nil, err return nil, err

View file

@ -5,7 +5,7 @@
package main package main
import ( import (
"github.com/btcsuite/btcchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcwire" "github.com/btcsuite/btcwire"
) )
@ -13,7 +13,8 @@ import (
// processing of a transaction failed due to one of the many validation // processing of a transaction failed due to one of the many validation
// rules. The caller can use type assertions to determine if a failure was // rules. The caller can use type assertions to determine if a failure was
// specifically due to a rule violation and use the Err field to access the // specifically due to a rule violation and use the Err field to access the
// underlying error, which will be either a TxRuleError or a btcchain.RuleError. // underlying error, which will be either a TxRuleError or a
// blockchain.RuleError.
type RuleError struct { type RuleError struct {
Err error Err error
} }
@ -50,8 +51,8 @@ func txRuleError(c btcwire.RejectCode, desc string) RuleError {
} }
// chainRuleError returns a RuleError that encapsulates the given // chainRuleError returns a RuleError that encapsulates the given
// btcchain.RuleError. // blockchain.RuleError.
func chainRuleError(chainErr btcchain.RuleError) RuleError { func chainRuleError(chainErr blockchain.RuleError) RuleError {
return RuleError{ return RuleError{
Err: chainErr, Err: chainErr,
} }
@ -67,28 +68,28 @@ func extractRejectCode(err error) (btcwire.RejectCode, bool) {
} }
switch err := err.(type) { switch err := err.(type) {
case btcchain.RuleError: case blockchain.RuleError:
// Convert the chain error to a reject code. // Convert the chain error to a reject code.
var code btcwire.RejectCode var code btcwire.RejectCode
switch err.ErrorCode { switch err.ErrorCode {
// Rejected due to duplicate. // Rejected due to duplicate.
case btcchain.ErrDuplicateBlock: case blockchain.ErrDuplicateBlock:
fallthrough fallthrough
case btcchain.ErrDoubleSpend: case blockchain.ErrDoubleSpend:
code = btcwire.RejectDuplicate code = btcwire.RejectDuplicate
// Rejected due to obsolete version. // Rejected due to obsolete version.
case btcchain.ErrBlockVersionTooOld: case blockchain.ErrBlockVersionTooOld:
code = btcwire.RejectObsolete code = btcwire.RejectObsolete
// Rejected due to checkpoint. // Rejected due to checkpoint.
case btcchain.ErrCheckpointTimeTooOld: case blockchain.ErrCheckpointTimeTooOld:
fallthrough fallthrough
case btcchain.ErrDifficultyTooLow: case blockchain.ErrDifficultyTooLow:
fallthrough fallthrough
case btcchain.ErrBadCheckpoint: case blockchain.ErrBadCheckpoint:
fallthrough fallthrough
case btcchain.ErrForkTooOld: case blockchain.ErrForkTooOld:
code = btcwire.RejectCheckpoint code = btcwire.RejectCheckpoint
// Everything else is due to the block or transaction being invalid. // Everything else is due to the block or transaction being invalid.

View file

@ -10,7 +10,7 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/btcsuite/btcchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
@ -186,7 +186,7 @@ func minInt(a, b int) int {
// mergeTxStore adds all of the transactions in txStoreB to txStoreA. The // mergeTxStore adds all of the transactions in txStoreB to txStoreA. The
// result is that txStoreA will contain all of its original transactions plus // result is that txStoreA will contain all of its original transactions plus
// all of the transactions in txStoreB. // all of the transactions in txStoreB.
func mergeTxStore(txStoreA btcchain.TxStore, txStoreB btcchain.TxStore) { func mergeTxStore(txStoreA blockchain.TxStore, txStoreB blockchain.TxStore) {
for hash, txDataB := range txStoreB { for hash, txDataB := range txStoreB {
if txDataA, exists := txStoreA[hash]; !exists || if txDataA, exists := txStoreA[hash]; !exists ||
(txDataA.Err == database.ErrTxShaMissing && (txDataA.Err == database.ErrTxShaMissing &&
@ -242,7 +242,7 @@ func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int64, addr btcutil
Sequence: btcwire.MaxTxInSequenceNum, Sequence: btcwire.MaxTxInSequenceNum,
}) })
tx.AddTxOut(&btcwire.TxOut{ tx.AddTxOut(&btcwire.TxOut{
Value: btcchain.CalcBlockSubsidy(nextBlockHeight, Value: blockchain.CalcBlockSubsidy(nextBlockHeight,
activeNetParams.Params), activeNetParams.Params),
PkScript: pkScript, PkScript: pkScript,
}) })
@ -290,7 +290,7 @@ func calcPriority(tx *btcutil.Tx, serializedTxSize int, inputValueAge float64) f
// spendTransaction updates the passed transaction store by marking the inputs // spendTransaction updates the passed transaction store by marking the inputs
// to the passed transaction as spent. It also adds the passed transaction to // to the passed transaction as spent. It also adds the passed transaction to
// the store at the provided height. // the store at the provided height.
func spendTransaction(txStore btcchain.TxStore, tx *btcutil.Tx, height int64) error { func spendTransaction(txStore blockchain.TxStore, tx *btcutil.Tx, height int64) error {
for _, txIn := range tx.MsgTx().TxIn { for _, txIn := range tx.MsgTx().TxIn {
originHash := &txIn.PreviousOutPoint.Hash originHash := &txIn.PreviousOutPoint.Hash
originIndex := txIn.PreviousOutPoint.Index originIndex := txIn.PreviousOutPoint.Index
@ -299,7 +299,7 @@ func spendTransaction(txStore btcchain.TxStore, tx *btcutil.Tx, height int64) er
} }
} }
txStore[*tx.Sha()] = &btcchain.TxData{ txStore[*tx.Sha()] = &blockchain.TxData{
Tx: tx, Tx: tx,
Hash: tx.Sha(), Hash: tx.Sha(),
BlockHeight: height, BlockHeight: height,
@ -453,7 +453,7 @@ func NewBlockTemplate(mempool *txMemPool, payToAddress btcutil.Address) (*BlockT
if err != nil { if err != nil {
return nil, err return nil, err
} }
numCoinbaseSigOps := int64(btcchain.CountSigOps(coinbaseTx)) numCoinbaseSigOps := int64(blockchain.CountSigOps(coinbaseTx))
// Get the current memory pool transactions and create a priority queue // Get the current memory pool transactions and create a priority queue
// to hold the transactions which are ready for inclusion into a block // to hold the transactions which are ready for inclusion into a block
@ -472,7 +472,7 @@ func NewBlockTemplate(mempool *txMemPool, payToAddress btcutil.Address) (*BlockT
// can be avoided. // can be avoided.
blockTxns := make([]*btcutil.Tx, 0, len(mempoolTxns)) blockTxns := make([]*btcutil.Tx, 0, len(mempoolTxns))
blockTxns = append(blockTxns, coinbaseTx) blockTxns = append(blockTxns, coinbaseTx)
blockTxStore := make(btcchain.TxStore) blockTxStore := make(blockchain.TxStore)
// dependers is used to track transactions which depend on another // dependers is used to track transactions which depend on another
// transaction in the memory pool. This, in conjunction with the // transaction in the memory pool. This, in conjunction with the
@ -500,11 +500,11 @@ mempoolLoop:
// A block can't have more than one coinbase or contain // A block can't have more than one coinbase or contain
// non-finalized transactions. // non-finalized transactions.
tx := txDesc.Tx tx := txDesc.Tx
if btcchain.IsCoinBase(tx) { if blockchain.IsCoinBase(tx) {
minrLog.Tracef("Skipping coinbase tx %s", tx.Sha()) minrLog.Tracef("Skipping coinbase tx %s", tx.Sha())
continue continue
} }
if !btcchain.IsFinalizedTransaction(tx, nextBlockHeight, time.Now()) { if !blockchain.IsFinalizedTransaction(tx, nextBlockHeight, time.Now()) {
minrLog.Tracef("Skipping non-finalized tx %s", tx.Sha()) minrLog.Tracef("Skipping non-finalized tx %s", tx.Sha())
continue continue
} }
@ -632,15 +632,15 @@ mempoolLoop:
// Enforce maximum signature operations per block. Also check // Enforce maximum signature operations per block. Also check
// for overflow. // for overflow.
numSigOps := int64(btcchain.CountSigOps(tx)) numSigOps := int64(blockchain.CountSigOps(tx))
if blockSigOps+numSigOps < blockSigOps || if blockSigOps+numSigOps < blockSigOps ||
blockSigOps+numSigOps > btcchain.MaxSigOpsPerBlock { blockSigOps+numSigOps > blockchain.MaxSigOpsPerBlock {
minrLog.Tracef("Skipping tx %s because it would "+ minrLog.Tracef("Skipping tx %s because it would "+
"exceed the maximum sigops per block", tx.Sha()) "exceed the maximum sigops per block", tx.Sha())
logSkippedDeps(tx, deps) logSkippedDeps(tx, deps)
continue continue
} }
numP2SHSigOps, err := btcchain.CountP2SHSigOps(tx, false, numP2SHSigOps, err := blockchain.CountP2SHSigOps(tx, false,
blockTxStore) blockTxStore)
if err != nil { if err != nil {
minrLog.Tracef("Skipping tx %s due to error in "+ minrLog.Tracef("Skipping tx %s due to error in "+
@ -650,7 +650,7 @@ mempoolLoop:
} }
numSigOps += int64(numP2SHSigOps) numSigOps += int64(numP2SHSigOps)
if blockSigOps+numSigOps < blockSigOps || if blockSigOps+numSigOps < blockSigOps ||
blockSigOps+numSigOps > btcchain.MaxSigOpsPerBlock { blockSigOps+numSigOps > blockchain.MaxSigOpsPerBlock {
minrLog.Tracef("Skipping tx %s because it would "+ minrLog.Tracef("Skipping tx %s because it would "+
"exceed the maximum sigops per block (p2sh)", "exceed the maximum sigops per block (p2sh)",
tx.Sha()) tx.Sha())
@ -703,7 +703,7 @@ mempoolLoop:
// Ensure the transaction inputs pass all of the necessary // Ensure the transaction inputs pass all of the necessary
// preconditions before allowing it to be added to the block. // preconditions before allowing it to be added to the block.
_, err = btcchain.CheckTransactionInputs(tx, nextBlockHeight, _, err = blockchain.CheckTransactionInputs(tx, nextBlockHeight,
blockTxStore) blockTxStore)
if err != nil { if err != nil {
minrLog.Tracef("Skipping tx %s due to error in "+ minrLog.Tracef("Skipping tx %s due to error in "+
@ -711,7 +711,7 @@ mempoolLoop:
logSkippedDeps(tx, deps) logSkippedDeps(tx, deps)
continue continue
} }
err = btcchain.ValidateTransactionScripts(tx, blockTxStore, err = blockchain.ValidateTransactionScripts(tx, blockTxStore,
standardScriptVerifyFlags) standardScriptVerifyFlags)
if err != nil { if err != nil {
minrLog.Tracef("Skipping tx %s due to error in "+ minrLog.Tracef("Skipping tx %s due to error in "+
@ -777,7 +777,7 @@ mempoolLoop:
} }
// Create a new block ready to be solved. // Create a new block ready to be solved.
merkles := btcchain.BuildMerkleTreeStore(blockTxns) merkles := blockchain.BuildMerkleTreeStore(blockTxns)
var msgBlock btcwire.MsgBlock var msgBlock btcwire.MsgBlock
msgBlock.Header = btcwire.BlockHeader{ msgBlock.Header = btcwire.BlockHeader{
Version: generatedBlockVersion, Version: generatedBlockVersion,
@ -804,7 +804,7 @@ mempoolLoop:
minrLog.Debugf("Created new block template (%d transactions, %d in "+ minrLog.Debugf("Created new block template (%d transactions, %d in "+
"fees, %d signature operations, %d bytes, target difficulty "+ "fees, %d signature operations, %d bytes, target difficulty "+
"%064x)", len(msgBlock.Transactions), totalFees, blockSigOps, "%064x)", len(msgBlock.Transactions), totalFees, blockSigOps,
blockSize, btcchain.CompactToBig(msgBlock.Header.Bits)) blockSize, blockchain.CompactToBig(msgBlock.Header.Bits))
return &BlockTemplate{ return &BlockTemplate{
block: &msgBlock, block: &msgBlock,
@ -853,11 +853,11 @@ func UpdateExtraNonce(msgBlock *btcwire.MsgBlock, blockHeight int64, extraNonce
if err != nil { if err != nil {
return err return err
} }
if len(coinbaseScript) > btcchain.MaxCoinbaseScriptLen { if len(coinbaseScript) > blockchain.MaxCoinbaseScriptLen {
return fmt.Errorf("coinbase transaction script length "+ return fmt.Errorf("coinbase transaction script length "+
"of %d is out of range (min: %d, max: %d)", "of %d is out of range (min: %d, max: %d)",
len(coinbaseScript), btcchain.MinCoinbaseScriptLen, len(coinbaseScript), blockchain.MinCoinbaseScriptLen,
btcchain.MaxCoinbaseScriptLen) blockchain.MaxCoinbaseScriptLen)
} }
msgBlock.Transactions[0].TxIn[0].SignatureScript = coinbaseScript msgBlock.Transactions[0].TxIn[0].SignatureScript = coinbaseScript
@ -867,7 +867,7 @@ func UpdateExtraNonce(msgBlock *btcwire.MsgBlock, blockHeight int64, extraNonce
// Recalculate the merkle root with the updated extra nonce. // Recalculate the merkle root with the updated extra nonce.
block := btcutil.NewBlock(msgBlock) block := btcutil.NewBlock(msgBlock)
merkles := btcchain.BuildMerkleTreeStore(block.Transactions()) merkles := blockchain.BuildMerkleTreeStore(block.Transactions())
msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1] msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1]
return nil return nil
} }

View file

@ -16,8 +16,8 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/btcsuite/btcchain"
"github.com/btcsuite/btcd/addrmgr" "github.com/btcsuite/btcd/addrmgr"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/bloom" "github.com/btcsuite/btcutil/bloom"
@ -608,7 +608,7 @@ func (p *peer) pushMerkleBlockMsg(sha *btcwire.ShaHash, doneChan, waitChan chan
// PushGetBlocksMsg sends a getblocks message for the provided block locator // PushGetBlocksMsg sends a getblocks message for the provided block locator
// and stop hash. It will ignore back-to-back duplicate requests. // and stop hash. It will ignore back-to-back duplicate requests.
func (p *peer) PushGetBlocksMsg(locator btcchain.BlockLocator, stopHash *btcwire.ShaHash) error { func (p *peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *btcwire.ShaHash) error {
// Extract the begin hash from the block locator, if one was specified, // Extract the begin hash from the block locator, if one was specified,
// to use for filtering duplicate getblocks requests. // to use for filtering duplicate getblocks requests.
// request. // request.
@ -646,7 +646,7 @@ func (p *peer) PushGetBlocksMsg(locator btcchain.BlockLocator, stopHash *btcwire
// PushGetHeadersMsg sends a getblocks message for the provided block locator // PushGetHeadersMsg sends a getblocks message for the provided block locator
// and stop hash. It will ignore back-to-back duplicate requests. // and stop hash. It will ignore back-to-back duplicate requests.
func (p *peer) PushGetHeadersMsg(locator btcchain.BlockLocator, stopHash *btcwire.ShaHash) error { func (p *peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *btcwire.ShaHash) error {
// Extract the begin hash from the block locator, if one was specified, // Extract the begin hash from the block locator, if one was specified,
// to use for filtering duplicate getheaders requests. // to use for filtering duplicate getheaders requests.
var beginHash *btcwire.ShaHash var beginHash *btcwire.ShaHash

View file

@ -26,7 +26,7 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/btcsuite/btcchain" "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcec" "github.com/btcsuite/btcec"
@ -259,12 +259,12 @@ type gbtWorkState struct {
minTimestamp time.Time minTimestamp time.Time
template *BlockTemplate template *BlockTemplate
notifyMap map[btcwire.ShaHash]map[int64]chan struct{} notifyMap map[btcwire.ShaHash]map[int64]chan struct{}
timeSource btcchain.MedianTimeSource timeSource blockchain.MedianTimeSource
} }
// newGbtWorkState returns a new instance of a gbtWorkState with all internal // newGbtWorkState returns a new instance of a gbtWorkState with all internal
// fields initialized and ready to use. // fields initialized and ready to use.
func newGbtWorkState(timeSource btcchain.MedianTimeSource) *gbtWorkState { func newGbtWorkState(timeSource blockchain.MedianTimeSource) *gbtWorkState {
return &gbtWorkState{ return &gbtWorkState{
notifyMap: make(map[btcwire.ShaHash]map[int64]chan struct{}), notifyMap: make(map[btcwire.ShaHash]map[int64]chan struct{}),
timeSource: timeSource, timeSource: timeSource,
@ -852,7 +852,7 @@ func createVinList(mtx *btcwire.MsgTx) []btcjson.Vin {
tx := btcutil.NewTx(mtx) tx := btcutil.NewTx(mtx)
vinList := make([]btcjson.Vin, len(mtx.TxIn)) vinList := make([]btcjson.Vin, len(mtx.TxIn))
for i, v := range mtx.TxIn { for i, v := range mtx.TxIn {
if btcchain.IsCoinBase(tx) { if blockchain.IsCoinBase(tx) {
vinList[i].Coinbase = hex.EncodeToString(v.SignatureScript) vinList[i].Coinbase = hex.EncodeToString(v.SignatureScript)
} else { } else {
vinList[i].Txid = v.PreviousOutPoint.Hash.String() vinList[i].Txid = v.PreviousOutPoint.Hash.String()
@ -1463,7 +1463,7 @@ func (state *gbtWorkState) updateBlockTemplate(s *rpcServer, useCoinbaseValue bo
template = blkTemplate template = blkTemplate
msgBlock = template.block msgBlock = template.block
targetDifficulty = fmt.Sprintf("%064x", targetDifficulty = fmt.Sprintf("%064x",
btcchain.CompactToBig(msgBlock.Header.Bits)) blockchain.CompactToBig(msgBlock.Header.Bits))
// Find the minimum allowed timestamp for the block based on the // Find the minimum allowed timestamp for the block based on the
// median timestamp of the last several blocks per the chain // median timestamp of the last several blocks per the chain
@ -1524,14 +1524,14 @@ func (state *gbtWorkState) updateBlockTemplate(s *rpcServer, useCoinbaseValue bo
// Update the merkle root. // Update the merkle root.
block := btcutil.NewBlock(template.block) block := btcutil.NewBlock(template.block)
merkles := btcchain.BuildMerkleTreeStore(block.Transactions()) merkles := blockchain.BuildMerkleTreeStore(block.Transactions())
template.block.Header.MerkleRoot = *merkles[len(merkles)-1] template.block.Header.MerkleRoot = *merkles[len(merkles)-1]
} }
// Set locals for convenience. // Set locals for convenience.
msgBlock = template.block msgBlock = template.block
targetDifficulty = fmt.Sprintf("%064x", targetDifficulty = fmt.Sprintf("%064x",
btcchain.CompactToBig(msgBlock.Header.Bits)) blockchain.CompactToBig(msgBlock.Header.Bits))
// Update the time of the block template to the current time // Update the time of the block template to the current time
// while accounting for the median time of the past several // while accounting for the median time of the past several
@ -1561,7 +1561,7 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld
msgBlock := template.block msgBlock := template.block
header := &msgBlock.Header header := &msgBlock.Header
adjustedTime := state.timeSource.AdjustedTime() adjustedTime := state.timeSource.AdjustedTime()
maxTime := adjustedTime.Add(time.Second * btcchain.MaxTimeOffsetSeconds) maxTime := adjustedTime.Add(time.Second * blockchain.MaxTimeOffsetSeconds)
if header.Timestamp.After(maxTime) { if header.Timestamp.After(maxTime) {
return nil, btcjson.Error{ return nil, btcjson.Error{
Code: btcjson.ErrOutOfRange.Code, Code: btcjson.ErrOutOfRange.Code,
@ -1627,14 +1627,14 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld
// implied by the included or omission of fields: // implied by the included or omission of fields:
// Including MinTime -> time/decrement // Including MinTime -> time/decrement
// Omitting CoinbaseTxn -> coinbase, generation // Omitting CoinbaseTxn -> coinbase, generation
targetDifficulty := fmt.Sprintf("%064x", btcchain.CompactToBig(header.Bits)) targetDifficulty := fmt.Sprintf("%064x", blockchain.CompactToBig(header.Bits))
templateID := encodeTemplateID(state.prevHash, state.lastGenerated) templateID := encodeTemplateID(state.prevHash, state.lastGenerated)
reply := btcjson.GetBlockTemplateResult{ reply := btcjson.GetBlockTemplateResult{
Bits: strconv.FormatInt(int64(header.Bits), 16), Bits: strconv.FormatInt(int64(header.Bits), 16),
CurTime: header.Timestamp.Unix(), CurTime: header.Timestamp.Unix(),
Height: template.height, Height: template.height,
PreviousHash: header.PrevBlock.String(), PreviousHash: header.PrevBlock.String(),
SigOpLimit: btcchain.MaxSigOpsPerBlock, SigOpLimit: blockchain.MaxSigOpsPerBlock,
SizeLimit: btcwire.MaxBlockPayload, SizeLimit: btcwire.MaxBlockPayload,
Transactions: transactions, Transactions: transactions,
Version: header.Version, Version: header.Version,
@ -1868,87 +1868,87 @@ func handleGetBlockTemplateRequest(s *rpcServer, request *btcjson.TemplateReques
func chainErrToGBTErrString(err error) string { func chainErrToGBTErrString(err error) string {
// When the passed error is not a RuleError, just return a generic // When the passed error is not a RuleError, just return a generic
// rejected string with the error text. // rejected string with the error text.
ruleErr, ok := err.(btcchain.RuleError) ruleErr, ok := err.(blockchain.RuleError)
if !ok { if !ok {
return "rejected: " + err.Error() return "rejected: " + err.Error()
} }
switch ruleErr.ErrorCode { switch ruleErr.ErrorCode {
case btcchain.ErrDuplicateBlock: case blockchain.ErrDuplicateBlock:
return "duplicate" return "duplicate"
case btcchain.ErrBlockTooBig: case blockchain.ErrBlockTooBig:
return "bad-block-size" return "bad-block-size"
case btcchain.ErrBlockVersionTooOld: case blockchain.ErrBlockVersionTooOld:
return "bad-version" return "bad-version"
case btcchain.ErrInvalidTime: case blockchain.ErrInvalidTime:
return "bad-time" return "bad-time"
case btcchain.ErrTimeTooOld: case blockchain.ErrTimeTooOld:
return "time-too-old" return "time-too-old"
case btcchain.ErrTimeTooNew: case blockchain.ErrTimeTooNew:
return "time-too-new" return "time-too-new"
case btcchain.ErrDifficultyTooLow: case blockchain.ErrDifficultyTooLow:
return "bad-diffbits" return "bad-diffbits"
case btcchain.ErrUnexpectedDifficulty: case blockchain.ErrUnexpectedDifficulty:
return "bad-diffbits" return "bad-diffbits"
case btcchain.ErrHighHash: case blockchain.ErrHighHash:
return "high-hash" return "high-hash"
case btcchain.ErrBadMerkleRoot: case blockchain.ErrBadMerkleRoot:
return "bad-txnmrklroot" return "bad-txnmrklroot"
case btcchain.ErrBadCheckpoint: case blockchain.ErrBadCheckpoint:
return "bad-checkpoint" return "bad-checkpoint"
case btcchain.ErrForkTooOld: case blockchain.ErrForkTooOld:
return "fork-too-old" return "fork-too-old"
case btcchain.ErrCheckpointTimeTooOld: case blockchain.ErrCheckpointTimeTooOld:
return "checkpoint-time-too-old" return "checkpoint-time-too-old"
case btcchain.ErrNoTransactions: case blockchain.ErrNoTransactions:
return "bad-txns-none" return "bad-txns-none"
case btcchain.ErrTooManyTransactions: case blockchain.ErrTooManyTransactions:
return "bad-txns-toomany" return "bad-txns-toomany"
case btcchain.ErrNoTxInputs: case blockchain.ErrNoTxInputs:
return "bad-txns-noinputs" return "bad-txns-noinputs"
case btcchain.ErrNoTxOutputs: case blockchain.ErrNoTxOutputs:
return "bad-txns-nooutputs" return "bad-txns-nooutputs"
case btcchain.ErrTxTooBig: case blockchain.ErrTxTooBig:
return "bad-txns-size" return "bad-txns-size"
case btcchain.ErrBadTxOutValue: case blockchain.ErrBadTxOutValue:
return "bad-txns-outputvalue" return "bad-txns-outputvalue"
case btcchain.ErrDuplicateTxInputs: case blockchain.ErrDuplicateTxInputs:
return "bad-txns-dupinputs" return "bad-txns-dupinputs"
case btcchain.ErrBadTxInput: case blockchain.ErrBadTxInput:
return "bad-txns-badinput" return "bad-txns-badinput"
case btcchain.ErrMissingTx: case blockchain.ErrMissingTx:
return "bad-txns-missinginput" return "bad-txns-missinginput"
case btcchain.ErrUnfinalizedTx: case blockchain.ErrUnfinalizedTx:
return "bad-txns-unfinalizedtx" return "bad-txns-unfinalizedtx"
case btcchain.ErrDuplicateTx: case blockchain.ErrDuplicateTx:
return "bad-txns-duplicate" return "bad-txns-duplicate"
case btcchain.ErrOverwriteTx: case blockchain.ErrOverwriteTx:
return "bad-txns-overwrite" return "bad-txns-overwrite"
case btcchain.ErrImmatureSpend: case blockchain.ErrImmatureSpend:
return "bad-txns-maturity" return "bad-txns-maturity"
case btcchain.ErrDoubleSpend: case blockchain.ErrDoubleSpend:
return "bad-txns-dblspend" return "bad-txns-dblspend"
case btcchain.ErrSpendTooHigh: case blockchain.ErrSpendTooHigh:
return "bad-txns-highspend" return "bad-txns-highspend"
case btcchain.ErrBadFees: case blockchain.ErrBadFees:
return "bad-txns-fees" return "bad-txns-fees"
case btcchain.ErrTooManySigOps: case blockchain.ErrTooManySigOps:
return "high-sigops" return "high-sigops"
case btcchain.ErrFirstTxNotCoinbase: case blockchain.ErrFirstTxNotCoinbase:
return "bad-txns-nocoinbase" return "bad-txns-nocoinbase"
case btcchain.ErrMultipleCoinbases: case blockchain.ErrMultipleCoinbases:
return "bad-txns-multicoinbase" return "bad-txns-multicoinbase"
case btcchain.ErrBadCoinbaseScriptLen: case blockchain.ErrBadCoinbaseScriptLen:
return "bad-cb-length" return "bad-cb-length"
case btcchain.ErrBadCoinbaseValue: case blockchain.ErrBadCoinbaseValue:
return "bad-cb-value" return "bad-cb-value"
case btcchain.ErrMissingCoinbaseHeight: case blockchain.ErrMissingCoinbaseHeight:
return "bad-cb-height" return "bad-cb-height"
case btcchain.ErrBadCoinbaseHeight: case blockchain.ErrBadCoinbaseHeight:
return "bad-cb-height" return "bad-cb-height"
case btcchain.ErrScriptMalformed: case blockchain.ErrScriptMalformed:
return "bad-script-malformed" return "bad-script-malformed"
case btcchain.ErrScriptValidation: case blockchain.ErrScriptValidation:
return "bad-script-validate" return "bad-script-validate"
} }
@ -1998,10 +1998,10 @@ func handleGetBlockTemplateProposal(s *rpcServer, request *btcjson.TemplateReque
return "bad-prevblk", nil return "bad-prevblk", nil
} }
flags := btcchain.BFDryRun | btcchain.BFNoPoWCheck flags := blockchain.BFDryRun | blockchain.BFNoPoWCheck
isOrphan, err := s.server.blockManager.ProcessBlock(block, flags) isOrphan, err := s.server.blockManager.ProcessBlock(block, flags)
if err != nil { if err != nil {
if _, ok := err.(btcchain.RuleError); !ok { if _, ok := err.(blockchain.RuleError); !ok {
rpcsLog.Errorf("Failed to process block proposal: %v", rpcsLog.Errorf("Failed to process block proposal: %v",
err) err)
return nil, btcjson.Error{ return nil, btcjson.Error{
@ -2213,7 +2213,7 @@ func handleGetNetworkHashPS(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan stru
// starting height is not before the beginning of the chain. // starting height is not before the beginning of the chain.
var startHeight int64 var startHeight int64
if c.Blocks <= 0 { if c.Blocks <= 0 {
startHeight = endHeight - ((endHeight % btcchain.BlocksPerRetarget) + 1) startHeight = endHeight - ((endHeight % blockchain.BlocksPerRetarget) + 1)
} else { } else {
startHeight = endHeight - int64(c.Blocks) startHeight = endHeight - int64(c.Blocks)
} }
@ -2248,7 +2248,7 @@ func handleGetNetworkHashPS(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan stru
minTimestamp = header.Timestamp minTimestamp = header.Timestamp
maxTimestamp = minTimestamp maxTimestamp = minTimestamp
} else { } else {
totalWork.Add(totalWork, btcchain.CalcWork(header.Bits)) totalWork.Add(totalWork, blockchain.CalcWork(header.Bits))
if minTimestamp.After(header.Timestamp) { if minTimestamp.After(header.Timestamp) {
minTimestamp = header.Timestamp minTimestamp = header.Timestamp
@ -2543,7 +2543,7 @@ func handleGetTxOut(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{}) (i
Type: scriptClass.String(), Type: scriptClass.String(),
Addresses: addresses, Addresses: addresses,
}, },
Coinbase: btcchain.IsCoinBase(btcutil.NewTx(mtx)), Coinbase: blockchain.IsCoinBase(btcutil.NewTx(mtx)),
} }
return txOutReply, nil return txOutReply, nil
} }
@ -2605,7 +2605,7 @@ func handleGetWorkRequest(s *rpcServer) (interface{}, error) {
"nonce %d, target %064x, merkle root %s, signature "+ "nonce %d, target %064x, merkle root %s, signature "+
"script %x)", msgBlock.Header.Timestamp, "script %x)", msgBlock.Header.Timestamp,
state.extraNonce, state.extraNonce,
btcchain.CompactToBig(msgBlock.Header.Bits), blockchain.CompactToBig(msgBlock.Header.Bits),
msgBlock.Header.MerkleRoot, msgBlock.Header.MerkleRoot,
msgBlock.Transactions[0].TxIn[0].SignatureScript) msgBlock.Transactions[0].TxIn[0].SignatureScript)
} else { } else {
@ -2641,7 +2641,7 @@ func handleGetWorkRequest(s *rpcServer) (interface{}, error) {
"nonce %d, target %064x, merkle root %s, signature "+ "nonce %d, target %064x, merkle root %s, signature "+
"script %x)", msgBlock.Header.Timestamp, "script %x)", msgBlock.Header.Timestamp,
state.extraNonce, state.extraNonce,
btcchain.CompactToBig(msgBlock.Header.Bits), blockchain.CompactToBig(msgBlock.Header.Bits),
msgBlock.Header.MerkleRoot, msgBlock.Header.MerkleRoot,
msgBlock.Transactions[0].TxIn[0].SignatureScript) msgBlock.Transactions[0].TxIn[0].SignatureScript)
} }
@ -2715,7 +2715,7 @@ func handleGetWorkRequest(s *rpcServer) (interface{}, error) {
reverseUint32Array(data) reverseUint32Array(data)
reverseUint32Array(hash1[:]) reverseUint32Array(hash1[:])
reverseUint32Array(midstate[:]) reverseUint32Array(midstate[:])
target := bigToLEUint256(btcchain.CompactToBig(msgBlock.Header.Bits)) target := bigToLEUint256(blockchain.CompactToBig(msgBlock.Header.Bits))
reply := &btcjson.GetWorkResult{ reply := &btcjson.GetWorkResult{
Data: hex.EncodeToString(data), Data: hex.EncodeToString(data),
Hash1: hex.EncodeToString(hash1[:]), Hash1: hex.EncodeToString(hash1[:]),
@ -2788,15 +2788,15 @@ func handleGetWorkSubmission(s *rpcServer, hexData string) (interface{}, error)
msgBlock.Header.Timestamp = submittedHeader.Timestamp msgBlock.Header.Timestamp = submittedHeader.Timestamp
msgBlock.Header.Nonce = submittedHeader.Nonce msgBlock.Header.Nonce = submittedHeader.Nonce
msgBlock.Transactions[0].TxIn[0].SignatureScript = blockInfo.signatureScript msgBlock.Transactions[0].TxIn[0].SignatureScript = blockInfo.signatureScript
merkles := btcchain.BuildMerkleTreeStore(block.Transactions()) merkles := blockchain.BuildMerkleTreeStore(block.Transactions())
msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1] msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1]
// Ensure the submitted block hash is less than the target difficulty. // Ensure the submitted block hash is less than the target difficulty.
err = btcchain.CheckProofOfWork(block, activeNetParams.PowLimit) err = blockchain.CheckProofOfWork(block, activeNetParams.PowLimit)
if err != nil { if err != nil {
// Anything other than a rule violation is an unexpected error, // Anything other than a rule violation is an unexpected error,
// so return that error as an internal error. // so return that error as an internal error.
if _, ok := err.(btcchain.RuleError); !ok { if _, ok := err.(blockchain.RuleError); !ok {
return false, btcjson.Error{ return false, btcjson.Error{
Code: btcjson.ErrInternal.Code, Code: btcjson.ErrInternal.Code,
Message: fmt.Sprintf("Unexpected error while "+ Message: fmt.Sprintf("Unexpected error while "+
@ -2818,11 +2818,11 @@ func handleGetWorkSubmission(s *rpcServer, hexData string) (interface{}, error)
// Process this block using the same rules as blocks coming from other // Process this block using the same rules as blocks coming from other
// nodes. This will in turn relay it to the network like normal. // nodes. This will in turn relay it to the network like normal.
isOrphan, err := s.server.blockManager.ProcessBlock(block, btcchain.BFNone) isOrphan, err := s.server.blockManager.ProcessBlock(block, blockchain.BFNone)
if err != nil || isOrphan { if err != nil || isOrphan {
// Anything other than a rule violation is an unexpected error, // Anything other than a rule violation is an unexpected error,
// so return that error as an internal error. // so return that error as an internal error.
if _, ok := err.(btcchain.RuleError); !ok { if _, ok := err.(blockchain.RuleError); !ok {
return false, btcjson.Error{ return false, btcjson.Error{
Code: btcjson.ErrInternal.Code, Code: btcjson.ErrInternal.Code,
Message: fmt.Sprintf("Unexpected error while "+ Message: fmt.Sprintf("Unexpected error while "+
@ -3068,7 +3068,7 @@ func handleSubmitBlock(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{})
} }
} }
_, err = s.server.blockManager.ProcessBlock(block, btcchain.BFNone) _, err = s.server.blockManager.ProcessBlock(block, blockchain.BFNone)
if err != nil { if err != nil {
return fmt.Sprintf("rejected: %s", err.Error()), nil return fmt.Sprintf("rejected: %s", err.Error()), nil
} }
@ -3080,7 +3080,7 @@ func handleSubmitBlock(s *rpcServer, cmd btcjson.Cmd, closeChan <-chan struct{})
return nil, nil return nil, nil
} }
func verifyChain(db database.Db, level, depth int32, timeSource btcchain.MedianTimeSource) error { func verifyChain(db database.Db, level, depth int32, timeSource blockchain.MedianTimeSource) error {
_, curHeight64, err := db.NewestSha() _, curHeight64, err := db.NewestSha()
if err != nil { if err != nil {
rpcsLog.Errorf("Verify is unable to fetch current block "+ rpcsLog.Errorf("Verify is unable to fetch current block "+
@ -3113,7 +3113,7 @@ func verifyChain(db database.Db, level, depth int32, timeSource btcchain.MedianT
// Level 1 does basic chain sanity checks. // Level 1 does basic chain sanity checks.
if level > 0 { if level > 0 {
err := btcchain.CheckBlockSanity(block, err := blockchain.CheckBlockSanity(block,
activeNetParams.PowLimit, timeSource) activeNetParams.PowLimit, timeSource)
if err != nil { if err != nil {
rpcsLog.Errorf("Verify is unable to "+ rpcsLog.Errorf("Verify is unable to "+
@ -3284,8 +3284,8 @@ func getDifficultyRatio(bits uint32) float64 {
// converted back to a number. Note this is not the same as the the // converted back to a number. Note this is not the same as the the
// proof of work limit directly because the block difficulty is encoded // proof of work limit directly because the block difficulty is encoded
// in a block with the compact form which loses precision. // in a block with the compact form which loses precision.
max := btcchain.CompactToBig(activeNetParams.PowLimitBits) max := blockchain.CompactToBig(activeNetParams.PowLimitBits)
target := btcchain.CompactToBig(bits) target := blockchain.CompactToBig(bits)
difficulty := new(big.Rat).SetFrac(max, target) difficulty := new(big.Rat).SetFrac(max, target)
outString := difficulty.FloatString(2) outString := difficulty.FloatString(2)

View file

@ -19,8 +19,8 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/btcsuite/btcchain"
"github.com/btcsuite/btcd/addrmgr" "github.com/btcsuite/btcd/addrmgr"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcjson" "github.com/btcsuite/btcjson"
"github.com/btcsuite/btcnet" "github.com/btcsuite/btcnet"
@ -99,7 +99,7 @@ type server struct {
quit chan struct{} quit chan struct{}
nat NAT nat NAT
db database.Db db database.Db
timeSource btcchain.MedianTimeSource timeSource blockchain.MedianTimeSource
} }
type peerState struct { type peerState struct {
@ -1238,7 +1238,7 @@ func newServer(listenAddrs []string, db database.Db, netParams *btcnet.Params) (
modifyRebroadcastInv: make(chan interface{}), modifyRebroadcastInv: make(chan interface{}),
nat: nat, nat: nat,
db: db, db: db,
timeSource: btcchain.NewMedianTime(), timeSource: blockchain.NewMedianTime(),
} }
bm, err := newBlockManager(&s) bm, err := newBlockManager(&s)
if err != nil { if err != nil {