chaincfg

package
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 26, 2016 License: ISC Imports: 5 Imported by: 0

README

chaincfg

(http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org)

Package chaincfg defines chain configuration parameters for the three standard Decred networks and provides the ability for callers to define their own custom Decred networks.

Although this package was primarily written for dcrd, it has intentionally been designed so it can be used as a standalone package for any projects needing to use parameters for the standard Decred networks or for projects needing to define their own network.

Sample Use

package main

import (
	"flag"
	"fmt"
	"log"

	"github.com/decred/dcrutil"
	"github.com/decred/dcrd/chaincfg"
)

var testnet = flag.Bool("testnet", false, "operate on the testnet Decred network")

// By default (without -testnet), use mainnet.
var chainParams = &chaincfg.MainNetParams

func main() {
	flag.Parse()

	// Modify active network parameters if operating on testnet.
	if *testnet {
		chainParams = &chaincfg.TestNetParams
	}

	// later...

	// Create and print new payment address, specific to the active network.
	pubKeyHash := make([]byte, 20)
	addr, err := btcutil.NewAddressPubKeyHash(pubKeyHash, chainParams)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(addr)
}

Documentation

[GoDoc] (http://godoc.org/github.com/decred/dcrd/chaincfg)

Full go doc style documentation for the project can be viewed online without installing this package by using the GoDoc site here.

You can also view the documentation locally once the package is installed with the godoc tool by running godoc -http=":6060" and pointing your browser to http://localhost:6060/pkg/github.com/decred/dcrd/chaincfg

Installation

$ go get github.com/decred/dcrd/chaincfg

License

Package chaincfg is licensed under the copyfree ISC License.

Documentation

Overview

Package chaincfg defines chain configuration parameters.

In addition to the main Decred network, which is intended for the transfer of monetary value, there also exists two currently active standard networks: regression test and testnet (version 0). These networks are incompatible with each other (each sharing a different genesis block) and software should handle errors where input intended for one network is used on an application instance running on a different network.

For library packages, chaincfg provides the ability to lookup chain parameters and encoding magics when passed a *Params. Older APIs not updated to the new convention of passing a *Params may lookup the parameters for a wire.DecredNet using ParamsForNet, but be aware that this usage is deprecated and will be removed from chaincfg in the future.

For main packages, a (typically global) var may be assigned the address of one of the standard Param vars for use as the application's "active" network. When a network parameter is needed, it may then be looked up through this variable (either directly, or hidden in a library call).

package main

import (
        "flag"
        "fmt"
        "log"

        "github.com/decred/dcrutil"
        "github.com/decred/dcrd/chaincfg"
)

var testnet = flag.Bool("testnet", false, "operate on the testnet Decred network")

// By default (without -testnet), use mainnet.
var chainParams = &chaincfg.MainNetParams

func main() {
        flag.Parse()

        // Modify active network parameters if operating on testnet.
        if *testnet {
                chainParams = &chaincfg.TestNetParams
        }

        // later...

        // Create and print new payment address, specific to the active network.
        pubKeyHash := make([]byte, 20)
        addr, err := dcrutil.NewAddressPubKeyHash(pubKeyHash, chainParams)
        if err != nil {
                log.Fatal(err)
        }
        fmt.Println(addr)
}

If an application does not use one of the three standard Decred networks, a new Params struct may be created which defines the parameters for the non-standard network. As a general rule of thumb, all network parameters should be unique to the network, but parameter collisions can still occur (unfortunately, this is the case with regtest and testnet sharing magics).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDuplicateNet describes an error where the parameters for a Decred
	// network could not be set due to the network already being a standard
	// network or previously-registered into this package.
	ErrDuplicateNet = errors.New("duplicate Decred network")

	// ErrUnknownHDKeyID describes an error where the provided id which
	// is intended to identify the network for a hierarchical deterministic
	// private extended key is not registered.
	ErrUnknownHDKeyID = errors.New("unknown hd private extended key bytes")
)
View Source
var BlockOneLedgerMainNet = []*TokenPayout{}/* 3146 elements not displayed */

BlockOneLedgerMainNet is the block one output ledger for the main network.

View Source
var BlockOneLedgerSimNet = []*TokenPayout{
	&TokenPayout{"Sshw6S86G2bV6W32cbc7EhtFy8f93rU6pae", 100000 * 1e8},
	&TokenPayout{"SsjXRK6Xz6CFuBt6PugBvrkdAa4xGbcZ18w", 100000 * 1e8},
	&TokenPayout{"SsfXiYkYkCoo31CuVQw428N6wWKus2ZEw5X", 100000 * 1e8},
}

BlockOneLedgerSimNet is the block one output ledger for the simulation network. See under "Decred organization related parameters" in params.go for information on how to spend these outputs.

View Source
var BlockOneLedgerTestNet = []*TokenPayout{
	&TokenPayout{"TsmWaPM77WSyA3aiQ2Q1KnwGDVWvEkhipBc", 100000 * 1e8},
}

BlockOneLedgerTestNet is the block one output ledger for the test network.

View Source
var CPUMinerThreads = 1

CPUMinerThreads is the default number of threads to utilize with the CPUMiner when mining.

View Source
var MainNetParams = Params{
	Name:        "mainnet",
	Net:         wire.MainNet,
	DefaultPort: "9108",

	GenesisBlock:             &genesisBlock,
	GenesisHash:              &genesisHash,
	CurrentBlockVersion:      1,
	PowLimit:                 mainPowLimit,
	PowLimitBits:             0x1d00ffff,
	ResetMinDifficulty:       false,
	MinDiffResetTimeFactor:   0x7FFFFFFF,
	GenerateSupported:        false,
	MaximumBlockSize:         393216,
	TimePerBlock:             time.Minute * 5,
	WorkDiffAlpha:            1,
	WorkDiffWindowSize:       144,
	WorkDiffWindows:          20,
	TargetTimespan:           time.Minute * 5 * 144,
	RetargetAdjustmentFactor: 4,

	BaseSubsidy:           3119582664,
	MulSubsidy:            100,
	DivSubsidy:            101,
	ReductionInterval:     6144,
	WorkRewardProportion:  6,
	StakeRewardProportion: 3,
	BlockTaxProportion:    1,

	Checkpoints: []Checkpoint{
		{440, newHashFromStr("0000000000002203eb2c95ee96906730bb56b2985e174518f90eb4db29232d93")},
	},

	RelayNonStdTxs: false,

	NetworkAddressPrefix: "D",
	PubKeyAddrID:         [2]byte{0x13, 0x86},
	PubKeyHashAddrID:     [2]byte{0x07, 0x3f},
	PKHEdwardsAddrID:     [2]byte{0x07, 0x1f},
	PKHSchnorrAddrID:     [2]byte{0x07, 0x01},
	ScriptHashAddrID:     [2]byte{0x07, 0x1a},
	PrivateKeyID:         [2]byte{0x22, 0xde},

	HDPrivateKeyID: [4]byte{0x02, 0xfd, 0xa4, 0xe8},
	HDPublicKeyID:  [4]byte{0x02, 0xfd, 0xa9, 0x26},

	HDCoinType: 20,

	MinimumStakeDiff:      2 * 1e8,
	TicketPoolSize:        8192,
	TicketsPerBlock:       5,
	TicketMaturity:        256,
	TicketExpiry:          40960,
	CoinbaseMaturity:      256,
	SStxChangeMaturity:    1,
	TicketPoolSizeWeight:  4,
	StakeDiffAlpha:        1,
	StakeDiffWindowSize:   144,
	StakeDiffWindows:      20,
	MaxFreshStakePerBlock: 20,
	StakeEnabledHeight:    256 + 256,
	StakeValidationHeight: 4096,
	StakeBaseSigScript:    []byte{0x00, 0x00},

	OrganizationAddress: "Dcur2mcGjmENx4DhNqDctW5wJCVyT3Qeqkx",
	BlockOneLedger:      BlockOneLedgerMainNet,
}

MainNetParams defines the network parameters for the main Decred network.

View Source
var SigHashOptimization = false

SigHashOptimization is an optimization for verification of transactions that do CHECKSIG operations with hashType SIGHASH_ALL. Although there should be no consequences to daemons that are simply running a node, it may be the case that you could cause database corruption if you turn this code on, create and manipulate your own MsgTx, then include them in blocks. For safety, if you're using the daemon with wallet or mining with the daemon this should be disabled. If you believe that any MsgTxs in your daemon will be used mutably, do NOT turn on this feature. It is disabled by default. This feature is considered EXPERIMENTAL, enable at your own risk!

View Source
var SimNetParams = Params{
	Name:        "simnet",
	Net:         wire.SimNet,
	DefaultPort: "18555",

	GenesisBlock:             &simNetGenesisBlock,
	GenesisHash:              &simNetGenesisHash,
	CurrentBlockVersion:      0,
	PowLimit:                 simNetPowLimit,
	PowLimitBits:             0x207fffff,
	ResetMinDifficulty:       false,
	MinDiffResetTimeFactor:   0x7FFFFFFF,
	GenerateSupported:        true,
	MaximumBlockSize:         1000000,
	TimePerBlock:             time.Second * 1,
	WorkDiffAlpha:            1,
	WorkDiffWindowSize:       8,
	WorkDiffWindows:          4,
	TargetTimespan:           time.Second * 1 * 8,
	RetargetAdjustmentFactor: 4,

	BaseSubsidy:           50000000000,
	MulSubsidy:            100,
	DivSubsidy:            101,
	ReductionInterval:     128,
	WorkRewardProportion:  6,
	StakeRewardProportion: 3,
	BlockTaxProportion:    1,

	Checkpoints: nil,

	RelayNonStdTxs: true,

	NetworkAddressPrefix: "S",
	PubKeyAddrID:         [2]byte{0x27, 0x6f},
	PubKeyHashAddrID:     [2]byte{0x0e, 0x91},
	PKHEdwardsAddrID:     [2]byte{0x0e, 0x71},
	PKHSchnorrAddrID:     [2]byte{0x0e, 0x53},
	ScriptHashAddrID:     [2]byte{0x0e, 0x6c},
	PrivateKeyID:         [2]byte{0x23, 0x07},

	HDPrivateKeyID: [4]byte{0x04, 0x20, 0xb9, 0x03},
	HDPublicKeyID:  [4]byte{0x04, 0x20, 0xbd, 0x3d},

	HDCoinType: 115,

	MinimumStakeDiff:      20000,
	TicketPoolSize:        64,
	TicketsPerBlock:       5,
	TicketMaturity:        16,
	TicketExpiry:          384,
	CoinbaseMaturity:      16,
	SStxChangeMaturity:    1,
	TicketPoolSizeWeight:  4,
	StakeDiffAlpha:        1,
	StakeDiffWindowSize:   8,
	StakeDiffWindows:      8,
	MaxFreshStakePerBlock: 20,
	StakeEnabledHeight:    16 + 16,
	StakeValidationHeight: 16 + (64 * 2),
	StakeBaseSigScript:    []byte{0xDE, 0xAD, 0xBE, 0xEF},

	OrganizationAddress: "ScuQxvveKGfpG1ypt6u27F99Anf7EW3cqhq",
	BlockOneLedger:      BlockOneLedgerSimNet,
}

SimNetParams defines the network parameters for the simulation test Decred network. This network is similar to the normal test network except it is intended for private use within a group of individuals doing simulation testing. The functionality is intended to differ in that the only nodes which are specifically specified are used to create the network rather than following normal discovery rules. This is important as otherwise it would just turn into another public testnet.

View Source
var TestNetParams = Params{
	Name:        "testnet",
	Net:         wire.TestNet,
	DefaultPort: "19108",

	GenesisBlock:             &testNetGenesisBlock,
	GenesisHash:              &testNetGenesisHash,
	CurrentBlockVersion:      0,
	PowLimit:                 testNetPowLimit,
	PowLimitBits:             0x1e00ffff,
	ResetMinDifficulty:       false,
	MinDiffResetTimeFactor:   0x7FFFFFFF,
	GenerateSupported:        true,
	MaximumBlockSize:         1000000,
	TimePerBlock:             time.Minute * 2,
	WorkDiffAlpha:            1,
	WorkDiffWindowSize:       144,
	WorkDiffWindows:          20,
	TargetTimespan:           time.Minute * 2 * 144,
	RetargetAdjustmentFactor: 4,

	BaseSubsidy:           2500000000,
	MulSubsidy:            100,
	DivSubsidy:            101,
	ReductionInterval:     2048,
	WorkRewardProportion:  6,
	StakeRewardProportion: 3,
	BlockTaxProportion:    1,

	Checkpoints: []Checkpoint{},

	RelayNonStdTxs: true,

	NetworkAddressPrefix: "T",
	PubKeyAddrID:         [2]byte{0x28, 0xf7},
	PubKeyHashAddrID:     [2]byte{0x0f, 0x21},
	PKHEdwardsAddrID:     [2]byte{0x0f, 0x01},
	PKHSchnorrAddrID:     [2]byte{0x0e, 0xe3},
	ScriptHashAddrID:     [2]byte{0x0e, 0xfc},
	PrivateKeyID:         [2]byte{0x23, 0x0e},

	HDPrivateKeyID: [4]byte{0x04, 0x35, 0x83, 0x97},
	HDPublicKeyID:  [4]byte{0x04, 0x35, 0x87, 0xd1},

	HDCoinType: 11,

	MinimumStakeDiff:      20000000,
	TicketPoolSize:        1024,
	TicketsPerBlock:       5,
	TicketMaturity:        16,
	TicketExpiry:          6144,
	CoinbaseMaturity:      16,
	SStxChangeMaturity:    1,
	TicketPoolSizeWeight:  4,
	StakeDiffAlpha:        1,
	StakeDiffWindowSize:   144,
	StakeDiffWindows:      20,
	MaxFreshStakePerBlock: 20,
	StakeEnabledHeight:    16 + 16,
	StakeValidationHeight: 768,
	StakeBaseSigScript:    []byte{0xDE, 0xAD, 0xBE, 0xEF},

	OrganizationAddress: "TcemyEtyHSg9L7jww7uihv9BJfKL6YGiZYn",
	BlockOneLedger:      BlockOneLedgerTestNet,
}

TestNetParams defines the network parameters for the test currency network. This network is sometimes simply called "testnet".

Functions

func HDPrivateKeyToPublicKeyID

func HDPrivateKeyToPublicKeyID(id []byte) ([]byte, error)

HDPrivateKeyToPublicKeyID accepts a private hierarchical deterministic extended key id and returns the associated public key id. When the provided id is not registered, the ErrUnknownHDKeyID error will be returned.

func IsPKHEdwardsAddrID

func IsPKHEdwardsAddrID(id [2]byte) bool

IsPKHEdwardsAddrID returns whether the id is an identifier know to prefix a pay-to-pubkey-hash Edwards address.

func IsPKHSchnorrAddrID

func IsPKHSchnorrAddrID(id [2]byte) bool

IsPKHSchnorrAddrID returns whether the id is an identifier know to prefix a pay-to-pubkey-hash secp256k1 Schnorr address.

func IsPubKeyAddrID

func IsPubKeyAddrID(id [2]byte) bool

IsPubKeyAddrID returns whether the id is an identifier known to prefix a pay-to-pubkey address on any default or registered network.

func IsPubKeyHashAddrID

func IsPubKeyHashAddrID(id [2]byte) bool

IsPubKeyHashAddrID returns whether the id is an identifier known to prefix a pay-to-pubkey-hash address on any default or registered network. This is used when decoding an address string into a specific address type. It is up to the caller to check both this and IsScriptHashAddrID and decide whether an address is a pubkey hash address, script hash address, neither, or undeterminable (if both return true).

func IsScriptHashAddrID

func IsScriptHashAddrID(id [2]byte) bool

IsScriptHashAddrID returns whether the id is an identifier known to prefix a pay-to-script-hash address on any default or registered network. This is used when decoding an address string into a specific address type. It is up to the caller to check both this and IsPubKeyHashAddrID and decide whether an address is a pubkey hash address, script hash address, neither, or undeterminable (if both return true).

func Register

func Register(params *Params) error

Register registers the network parameters for a Decred network. This may error with ErrDuplicateNet if the network is already registered (either due to a previous Register call, or the network being one of the default networks).

Network parameters should be registered into this package by a main package as early as possible. Then, library packages may lookup networks or network parameters based on inputs and work regardless of the network being standard or not.

Types

type Checkpoint

type Checkpoint struct {
	Height int64
	Hash   *chainhash.Hash
}

Checkpoint identifies a known good point in the block chain. Using checkpoints allows a few optimizations for old blocks during initial download and also prevents forks from old blocks.

Each checkpoint is selected based upon several factors. See the documentation for chain.IsCheckpointCandidate for details on the selection criteria.

type Params

type Params struct {
	Name        string
	Net         wire.CurrencyNet
	DefaultPort string

	// Starting block for the network (block 0).
	GenesisBlock *wire.MsgBlock

	// Starting block hash.
	GenesisHash *chainhash.Hash

	// The version of the block that the majority of the network is currently
	// on.
	CurrentBlockVersion int32

	// Maximum value for nbits (minimum Proof of Work) as a uint256.
	PowLimit *big.Int

	// Maximum value for nbits (minimum Proof of Work) in compact form.
	PowLimitBits uint32

	// Testnet difficulty reset flag.
	ResetMinDifficulty bool

	// MinDiffResetTimeFactor is the amount to multiply TimePerBlock by to
	// reset the difficulty to the minimum network factor.
	MinDiffResetTimeFactor time.Duration

	// GenerateSupported specifies whether or not CPU mining is allowed.
	GenerateSupported bool

	// MaximumBlockSize is the maximum size of a block that can be generated
	// on the network.
	MaximumBlockSize int

	// TimePerBlock is the desired amount of time to generate each block in
	// minutes.
	TimePerBlock time.Duration

	// WorkDiffAlpha is the stake difficulty EMA calculation alpha (smoothing)
	// value. It is different from a normal EMA alpha. Closer to 1 --> smoother.
	WorkDiffAlpha int64

	// WorkDiffWindowSize is the number of windows (intervals) used for calculation
	// of the exponentially weighted average.
	WorkDiffWindowSize int64

	// WorkDiffWindows is the number of windows (intervals) used for calculation
	// of the exponentially weighted average.
	WorkDiffWindows int64

	// targetTimespan is the desired amount of time that should elapse
	// before block difficulty requirement is examined to determine how
	// it should be changed in order to maintain the desired block
	// generation rate. This value should correspond to the product of
	// WorkDiffWindowSize and TimePerBlock above.
	TargetTimespan time.Duration

	// RetargetAdjustmentFactor is the adjustment factor used to limit
	// the minimum and maximum amount of adjustment that can occur between
	// difficulty retargets.
	RetargetAdjustmentFactor int64

	// BaseSubsidy is the starting subsidy amount for mined blocks.
	BaseSubsidy int64

	// Subsidy reduction multiplier.
	MulSubsidy int64

	// Subsidy reduction divisor.
	DivSubsidy int64

	// Reduction interval in blocks.
	ReductionInterval int64

	// WorkRewardProportion is the comparative amount of the subsidy given for
	// creating a block.
	WorkRewardProportion uint16

	// StakeRewardProportion is the comparative amount of the subsidy given for
	// casting stake votes (collectively, per block).
	StakeRewardProportion uint16

	// BlockTaxProportion is the inverse of the percentage of funds for each
	// block to allocate to the developer organization.
	// e.g. 10% --> 10 (or 1 / (1/10))
	// Special case: disable taxes with a value of 0
	BlockTaxProportion uint16

	// Checkpoints ordered from oldest to newest.
	Checkpoints []Checkpoint

	// Mempool parameters
	RelayNonStdTxs bool

	// NetworkAddressPrefix is the first letter of the network
	// for any given address encoded as a string.
	NetworkAddressPrefix string

	// Address encoding magics
	PubKeyAddrID     [2]byte // First 2 bytes of a P2PK address
	PubKeyHashAddrID [2]byte // First 2 bytes of a P2PKH address
	PKHEdwardsAddrID [2]byte // First 2 bytes of an Edwards P2PKH address
	PKHSchnorrAddrID [2]byte // First 2 bytes of a secp256k1 Schnorr P2PKH address
	ScriptHashAddrID [2]byte // First 2 bytes of a P2SH address
	PrivateKeyID     [2]byte // First 2 bytes of a WIF private key

	// BIP32 hierarchical deterministic extended key magics
	HDPrivateKeyID [4]byte
	HDPublicKeyID  [4]byte

	// BIP44 coin type used in the hierarchical deterministic path for
	// address generation.
	HDCoinType uint32

	// MinimumStakeDiff if the minimum amount of Atoms required to purchase a
	// stake ticket.
	MinimumStakeDiff int64

	// Ticket pool sizes for Decred PoS. This denotes the number of possible
	// buckets/number of different ticket numbers. It is also the number of
	// possible winner numbers there are.
	TicketPoolSize uint16

	// Average number of tickets per block for Decred PoS.
	TicketsPerBlock uint16

	// Number of blocks for tickets to mature (spendable at TicketMaturity+1).
	TicketMaturity uint16

	// Number of blocks for tickets to expire after they have matured. This MUST
	// be >= (StakeEnabledHeight + StakeValidationHeight).
	TicketExpiry uint32

	// Maturity for spending coinbase tx.
	CoinbaseMaturity uint16

	// Maturity for spending SStx change outputs.
	SStxChangeMaturity uint16

	// TicketPoolSizeWeight is the multiplicative weight applied to the
	// ticket pool size difference between a window period and its target
	// when determining the stake system.
	TicketPoolSizeWeight uint16

	// StakeDiffAlpha is the stake difficulty EMA calculation alpha (smoothing)
	// value. It is different from a normal EMA alpha. Closer to 1 --> smoother.
	StakeDiffAlpha int64

	// StakeDiffWindowSize is the number of blocks used for each interval in
	// exponentially weighted average.
	StakeDiffWindowSize int64

	// StakeDiffWindows is the number of windows (intervals) used for calculation
	// of the exponentially weighted average.
	StakeDiffWindows int64

	// MaxFreshStakePerBlock is the maximum number of new tickets that may be
	// submitted per block.
	MaxFreshStakePerBlock uint8

	// StakeEnabledHeight is the height in which the first ticket could possibly
	// mature.
	StakeEnabledHeight int64

	// StakeValidationHeight is the height at which votes (SSGen) are required
	// to add a new block to the top of the blockchain. This height is the
	// first block that will be voted on, but will include in itself no votes.
	StakeValidationHeight int64

	// StakeBaseSigScript is the consensus stakebase signature script for all
	// votes on the network. This isn't signed in any way, so without forcing
	// it to be this value miners/daemons could freely change it.
	StakeBaseSigScript []byte

	// OrganizationAddress is the static address for block taxes to be
	// distributed to in every block's coinbase. It should ideally be
	// a P2SH multisignature address.
	OrganizationAddress string

	// BlockOneLedger specifies the list of payouts in the coinbase of
	// block height 1. If there are no payouts to be given, set this
	// to an empty slice.
	BlockOneLedger []*TokenPayout
}

Params defines a Decred network by its parameters. These parameters may be used by Decred applications to differentiate networks as well as addresses and keys for one network from those intended for use on another network.

func (*Params) BlockOneSubsidy

func (p *Params) BlockOneSubsidy() int64

BlockOneSubsidy returns the total subsidy of block height 1 for the network.

func (*Params) TotalSubsidyProportions

func (p *Params) TotalSubsidyProportions() uint16

TotalSubsidyProportions is the sum of WorkReward, StakeReward, and BlockTax proportions.

type TokenPayout

type TokenPayout struct {
	Address string
	Amount  int64
}

TokenPayout is a payout for block 1 which specifies an address and an amount to pay to that address in a transaction output.

Directories

Path Synopsis
Package chainec provides wrapper functions to abstract the ec functions.
Package chainec provides wrapper functions to abstract the ec functions.
Package chainhash defines the hash functions used.
Package chainhash defines the hash functions used.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL