Skip to content

Commit

Permalink
Initial pass at updating to btcnet.
Browse files Browse the repository at this point in the history
This change modifies the params struct to embed a *btcnet.Params,
removing the old parameter fields that are handled by the btcnet
package.

Hardcoded network checks have also been removed in favor of modifying
behavior based on the current active net's parameters.

Not all library packages, notable btcutil and btcchain, have been
updated to use btcnet yet, but with this change, each package can be
updated one at a time since the active net's btcnet.Params are
available at each callsite.

ok @davecgh
  • Loading branch information
jrick committed May 23, 2014
1 parent 342d0a5 commit bcc7856
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 88 deletions.
4 changes: 2 additions & 2 deletions blockmanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -1487,14 +1487,14 @@ func loadBlockDB() (btcdb.Db, error) {
// Insert the appropriate genesis block for the bitcoin network being
// connected to if needed.
if height == -1 {
genesis := btcutil.NewBlock(activeNetParams.genesisBlock)
genesis := btcutil.NewBlock(activeNetParams.GenesisBlock)
_, err := db.InsertBlock(genesis)
if err != nil {
db.Close()
return nil, err
}
btcdLog.Infof("Inserted genesis block %v",
activeNetParams.genesisHash)
activeNetParams.GenesisHash)
height = 0
}

Expand Down
2 changes: 1 addition & 1 deletion btcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func btcdMain(serverChan chan<- *server) error {
})

// Create server and start it.
server, err := newServer(cfg.Listeners, db, activeNetParams.btcnet)
server, err := newServer(cfg.Listeners, db, activeNetParams.Params)
if err != nil {
// TODO(oga) this logging could do with some beautifying.
btcdLog.Errorf("Unable to start server on %v: %v",
Expand Down
14 changes: 6 additions & 8 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ const (
defaultLogLevel = "info"
defaultLogDirname = "logs"
defaultLogFilename = "btcd.log"
defaultBtcnet = btcwire.MainNet
defaultMaxPeers = 125
defaultBanDuration = time.Hour * 24
defaultMaxRPCClients = 10
Expand All @@ -49,7 +48,6 @@ var (
btcdHomeDir = btcutil.AppDataDir("btcd", false)
defaultConfigFile = filepath.Join(btcdHomeDir, defaultConfigFilename)
defaultDataDir = filepath.Join(btcdHomeDir, defaultDataDirname)
defaultListener = net.JoinHostPort("", netParams(defaultBtcnet).listenPort)
knownDbTypes = btcdb.SupportedDBs()
defaultRPCKeyFile = filepath.Join(btcdHomeDir, "rpc.key")
defaultRPCCertFile = filepath.Join(btcdHomeDir, "rpc.cert")
Expand Down Expand Up @@ -389,9 +387,9 @@ func loadConfig() (*config, []string, error) {
// Choose the active network params based on the testnet and regression
// test net flags.
if cfg.TestNet3 {
activeNetParams = netParams(btcwire.TestNet3)
activeNetParams = &testNet3Params
} else if cfg.RegressionTest {
activeNetParams = netParams(btcwire.TestNet)
activeNetParams = &regressionNetParams
}

// Append the network type to the data directory so it is "namespaced"
Expand All @@ -401,12 +399,12 @@ func loadConfig() (*config, []string, error) {
// means each individual piece of serialized data does not have to
// worry about changing names per network and such.
cfg.DataDir = cleanAndExpandPath(cfg.DataDir)
cfg.DataDir = filepath.Join(cfg.DataDir, activeNetParams.netName)
cfg.DataDir = filepath.Join(cfg.DataDir, netName(activeNetParams))

// Append the network type to the log directory so it is "namespaced"
// per network in the same fashion as the data directory.
cfg.LogDir = cleanAndExpandPath(cfg.LogDir)
cfg.LogDir = filepath.Join(cfg.LogDir, activeNetParams.netName)
cfg.LogDir = filepath.Join(cfg.LogDir, netName(activeNetParams))

// Special show command to list supported subsystems and exit.
if cfg.DebugLevel == "show" {
Expand Down Expand Up @@ -526,15 +524,15 @@ func loadConfig() (*config, []string, error) {
// Check keys are valid and saved parsed versions.
cfg.miningKeys = make([]btcutil.Address, 0, len(cfg.GetWorkKeys))
for _, strAddr := range cfg.GetWorkKeys {
addr, err := btcutil.DecodeAddress(strAddr, activeNetParams.btcnet)
addr, err := btcutil.DecodeAddress(strAddr, activeNetParams.Net)
if err != nil {
str := "%s: the specified getworkkey '%s' failed to decode: %v"
err := fmt.Errorf(str, "loadConfig", strAddr, err)
fmt.Fprintln(os.Stderr, err)
parser.WriteHelp(os.Stderr)
return nil, nil, err
}
if !addr.IsForNet(activeNetParams.btcnet) {
if !addr.IsForNet(activeNetParams.Net) {
str := "%s: the specified getworkkey '%s' is on the wrong network"
err := fmt.Errorf(str, "loadConfig", strAddr)
fmt.Fprintln(os.Stderr, err)
Expand Down
11 changes: 6 additions & 5 deletions mempool.go
Original file line number Diff line number Diff line change
Expand Up @@ -778,8 +778,9 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isOrphan *bool, isNe
}
nextBlockHeight := curHeight + 1

// Don't allow non-standard transactions on the main network.
if activeNetParams.btcnet == btcwire.MainNet {
// Don't allow non-standard transactions if the network parameters
// forbid their relaying.
if !activeNetParams.RelayNonStdTxs {
err := checkTransactionStandard(tx, nextBlockHeight)
if err != nil {
str := fmt.Sprintf("transaction %v is not a standard "+
Expand Down Expand Up @@ -844,9 +845,9 @@ func (mp *txMemPool) maybeAcceptTransaction(tx *btcutil.Tx, isOrphan *bool, isNe
return err
}

// Don't allow transactions with non-standard inputs on the main
// network.
if activeNetParams.btcnet == btcwire.MainNet {
// Don't allow transactions with non-standard inputs if the network
// parameters forbid their relaying.
if !activeNetParams.RelayNonStdTxs {
err := checkInputsStandard(tx, txStore)
if err != nil {
str := fmt.Sprintf("transaction %v has a non-standard "+
Expand Down
10 changes: 4 additions & 6 deletions mining.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int64, addr btcutil
})
tx.AddTxOut(&btcwire.TxOut{
Value: btcchain.CalcBlockSubsidy(nextBlockHeight,
activeNetParams.btcnet),
activeNetParams.Net),
PkScript: pkScript,
})
return btcutil.NewTx(tx), nil
Expand Down Expand Up @@ -787,11 +787,9 @@ func UpdateBlockTime(msgBlock *btcwire.MsgBlock, bManager *blockManager) error {
}
msgBlock.Header.Timestamp = newTimestamp

// Recalculate the required difficulty for the test networks since it
// can change based on time.
if activeNetParams.btcnet == btcwire.TestNet ||
activeNetParams.btcnet == btcwire.TestNet3 {

// If running on a network that requires recalculating the difficulty,
// do so now.
if activeNetParams.ResetMinDifficulty {
difficulty, err := bManager.CalcNextRequiredDifficulty(newTimestamp)
if err != nil {
return err
Expand Down
95 changes: 38 additions & 57 deletions params.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,22 @@
package main

import (
"github.com/conformal/btcchain"
"github.com/conformal/btcnet"
"github.com/conformal/btcwire"
"math/big"
)

// activeNetParams is a pointer to the parameters specific to the
// currently active bitcoin network.
var activeNetParams = netParams(defaultBtcnet)
var activeNetParams = &mainNetParams

// params is used to group parameters for various networks such as the main
// network and test networks.
type params struct {
netName string
btcnet btcwire.BitcoinNet
genesisBlock *btcwire.MsgBlock
genesisHash *btcwire.ShaHash
powLimit *big.Int
powLimitBits uint32
peerPort string
listenPort string
rpcPort string
dnsSeeds []string
*btcnet.Params
peerPort string
listenPort string
rpcPort string
dnsSeeds []string
}

// mainNetParams contains parameters specific to the main network
Expand All @@ -36,15 +30,10 @@ type params struct {
// it does not handle on to btcd. This approach allows the wallet process
// to emulate the full reference implementation RPC API.
var mainNetParams = params{
netName: "mainnet",
btcnet: btcwire.MainNet,
genesisBlock: btcchain.ChainParams(btcwire.MainNet).GenesisBlock,
genesisHash: btcchain.ChainParams(btcwire.MainNet).GenesisHash,
powLimit: btcchain.ChainParams(btcwire.MainNet).PowLimit,
powLimitBits: btcchain.ChainParams(btcwire.MainNet).PowLimitBits,
listenPort: btcwire.MainPort,
peerPort: btcwire.MainPort,
rpcPort: "8334",
Params: &btcnet.MainNetParams,
listenPort: btcwire.MainPort,
peerPort: btcwire.MainPort,
rpcPort: "8334",
dnsSeeds: []string{
"seed.bitcoin.sipa.be",
"dnsseed.bluematt.me",
Expand All @@ -55,54 +44,46 @@ var mainNetParams = params{
},
}

// regressionParams contains parameters specific to the regression test network
// (btcwire.TestNet). NOTE: The RPC port is intentionally different than the
// reference implementation - see the mainNetParams comment for details.
var regressionParams = params{
netName: "regtest",
btcnet: btcwire.TestNet,
genesisBlock: btcchain.ChainParams(btcwire.TestNet).GenesisBlock,
genesisHash: btcchain.ChainParams(btcwire.TestNet).GenesisHash,
powLimit: btcchain.ChainParams(btcwire.TestNet).PowLimit,
powLimitBits: btcchain.ChainParams(btcwire.TestNet).PowLimitBits,
listenPort: btcwire.RegressionTestPort,
peerPort: btcwire.TestNetPort,
rpcPort: "18334",
dnsSeeds: []string{},
// regressionNetParams contains parameters specific to the regression test
// network (btcwire.TestNet). NOTE: The RPC port is intentionally different
// than the reference implementation - see the mainNetParams comment for
// details.
var regressionNetParams = params{
Params: &btcnet.RegressionNetParams,
listenPort: btcwire.RegressionTestPort,
peerPort: btcwire.TestNetPort,
rpcPort: "18334",
dnsSeeds: []string{},
}

// testNet3Params contains parameters specific to the test network (version 3)
// (btcwire.TestNet3). NOTE: The RPC port is intentionally different than the
// reference implementation - see the mainNetParams comment for details.
var testNet3Params = params{
netName: "testnet",
btcnet: btcwire.TestNet3,
genesisBlock: btcchain.ChainParams(btcwire.TestNet3).GenesisBlock,
genesisHash: btcchain.ChainParams(btcwire.TestNet3).GenesisHash,
powLimit: btcchain.ChainParams(btcwire.TestNet3).PowLimit,
powLimitBits: btcchain.ChainParams(btcwire.TestNet3).PowLimitBits,
listenPort: btcwire.TestNetPort,
peerPort: btcwire.TestNetPort,
rpcPort: "18334",
Params: &btcnet.TestNet3Params,
listenPort: btcwire.TestNetPort,
peerPort: btcwire.TestNetPort,
rpcPort: "18334",
dnsSeeds: []string{
"testnet-seed.bitcoin.petertodd.org",
"testnet-seed.bluematt.me",
},
}

// netParams returns parameters specific to the passed bitcoin network.
func netParams(btcnet btcwire.BitcoinNet) *params {
switch btcnet {
case btcwire.TestNet:
return &regressionParams

// netName returns the name used when referring to a bitcoin network. At the
// time of writing, btcd currently places blocks for testnet version 3 in the
// data and log directory "testnet", which does not match the Name field of the
// btcnet parameters. This function can be used to override this directory name
// as "testnet" when the passed active network matches btcwire.TestNet3.
//
// A proper upgrade to move the data and log directories for this network to
// "testnet3" is planned for the future, at which point this function can be
// removed and the network parameter's name used instead.
func netName(netParams *params) string {
switch netParams.Net {
case btcwire.TestNet3:
return &testNet3Params

// Return main net by default.
case btcwire.MainNet:
fallthrough
return "testnet"
default:
return &mainNetParams
return netParams.Name
}
}
8 changes: 4 additions & 4 deletions rpcserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,7 @@ func handleCreateRawTransaction(s *rpcServer, cmd btcjson.Cmd) (interface{}, err

// Decode the provided address.
addr, err := btcutil.DecodeAddress(encodedAddr,
activeNetParams.btcnet)
activeNetParams.Net)
if err != nil {
return nil, btcjson.Error{
Code: btcjson.ErrInvalidAddressOrKey.Code,
Expand Down Expand Up @@ -1710,7 +1710,7 @@ func handleGetWorkSubmission(s *rpcServer, hexData string) (interface{}, error)
msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1]

// Ensure the submitted block hash is less than the target difficulty.
err = btcchain.CheckProofOfWork(block, activeNetParams.powLimit)
err = btcchain.CheckProofOfWork(block, activeNetParams.PowLimit)
if err != nil {
// Anything other than a rule violation is an unexpected error,
// so return that error as an internal error.
Expand Down Expand Up @@ -1998,7 +1998,7 @@ func verifyChain(db btcdb.Db, level, depth int32) error {
// Level 1 does basic chain sanity checks.
if level > 0 {
err := btcchain.CheckBlockSanity(block,
activeNetParams.powLimit)
activeNetParams.PowLimit)
if err != nil {
rpcsLog.Errorf("Verify is unable to "+
"validate block at sha %v height "+
Expand Down Expand Up @@ -2088,7 +2088,7 @@ func getDifficultyRatio(bits uint32) float64 {
// 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
// in a block with the compact form which loses precision.
max := btcchain.CompactToBig(activeNetParams.powLimitBits)
max := btcchain.CompactToBig(activeNetParams.PowLimitBits)
target := btcchain.CompactToBig(bits)

difficulty := new(big.Rat).SetFrac(max, target)
Expand Down
4 changes: 2 additions & 2 deletions rpcwebsocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -1433,7 +1433,7 @@ func handleNotifyReceived(wsc *wsClient, icmd btcjson.Cmd) (interface{}, *btcjso
}

for _, addrStr := range cmd.Addresses {
addr, err := btcutil.DecodeAddress(addrStr, activeNetParams.btcnet)
addr, err := btcutil.DecodeAddress(addrStr, activeNetParams.Net)
if err != nil {
e := btcjson.Error{
Code: btcjson.ErrInvalidAddressOrKey.Code,
Expand Down Expand Up @@ -1630,7 +1630,7 @@ func handleRescan(wsc *wsClient, icmd btcjson.Cmd) (interface{}, *btcjson.Error)
var compressedPubkey [33]byte
var uncompressedPubkey [65]byte
for _, addrStr := range cmd.Addresses {
addr, err := btcutil.DecodeAddress(addrStr, activeNetParams.btcnet)
addr, err := btcutil.DecodeAddress(addrStr, activeNetParams.Net)
if err != nil {
jsonErr := btcjson.Error{
Code: btcjson.ErrInvalidAddressOrKey.Code,
Expand Down
7 changes: 4 additions & 3 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"fmt"
"github.com/conformal/btcdb"
"github.com/conformal/btcjson"
"github.com/conformal/btcnet"
"github.com/conformal/btcwire"
"math"
"net"
Expand Down Expand Up @@ -1003,9 +1004,9 @@ out:
}

// newServer returns a new btcd server configured to listen on addr for the
// bitcoin network type specified in btcnet. Use start to begin accepting
// bitcoin network type specified by netParams. Use start to begin accepting
// connections from peers.
func newServer(listenAddrs []string, db btcdb.Db, btcnet btcwire.BitcoinNet) (*server, error) {
func newServer(listenAddrs []string, db btcdb.Db, netParams *btcnet.Params) (*server, error) {
nonce, err := btcwire.RandomUint64()
if err != nil {
return nil, err
Expand Down Expand Up @@ -1128,7 +1129,7 @@ func newServer(listenAddrs []string, db btcdb.Db, btcnet btcwire.BitcoinNet) (*s
s := server{
nonce: nonce,
listeners: listeners,
btcnet: btcnet,
btcnet: netParams.Net,
addrManager: amgr,
newPeers: make(chan *peer, cfg.MaxPeers),
donePeers: make(chan *peer, cfg.MaxPeers),
Expand Down

0 comments on commit bcc7856

Please sign in to comment.