chaincfg

package
v0.0.0-...-8237298 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2019 License: ISC Imports: 8 Imported by: 0

README

chaincfg

Build Status ISC License GoDoc

Package chaincfg defines chain configuration parameters for the four standard Utopia networks.

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

Sample Use

package main

import (
	"flag"
	"fmt"
	"log"

	"github.com/UtopiaCoinOrg/ucd/ucutil"
	"github.com/UtopiaCoinOrg/ucd/chaincfg"
)

var testnet = flag.Bool("testnet", false, "operate on the testnet Utopia 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.TestNet3Params()
	}

	// 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)
}

Installation and Updating

$ go get -u github.com/UtopiaCoinOrg/ucd/chaincfg

License

Package chaincfg is licensed under the copyfree ISC License.

Documentation

Overview

Package chaincfg defines chain configuration parameters.

In addition to the main Utopia 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.UtopiaNet 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/UtopiaCoinOrg/ucd/ucutil"
        "github.com/UtopiaCoinOrg/ucd/chaincfg"
)

var testnet = flag.Bool("testnet", false, "operate on the testnet Utopia 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.TestNet3Params()
        }

        // later...

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

If an application does not use one of the standard Utopia 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.

Index

Constants

View Source
const (
	// VoteIDMaxBlockSize is the vote ID for the the maximum block size
	// increase agenda used for the hard fork demo.
	VoteIDMaxBlockSize = "maxblocksize"

	// VoteIDSDiffAlgorithm is the vote ID for the new stake difficulty
	// algorithm (aka ticket price) agenda defined by DCP0001.
	VoteIDSDiffAlgorithm = "sdiffalgorithm"

	// VoteIDLNSupport is the vote ID for determining if the developers
	// should work on integrating Lightning Network support.
	VoteIDLNSupport = "lnsupport"

	// VoteIDLNFeatures is the vote ID for the agenda that introduces
	// features useful for the Lightning Network (among other uses) defined
	// by DCP0002 and DCP0003.
	VoteIDLNFeatures = "lnfeatures"

	// VoteIDFixLNSeqLocks is the vote ID for the agenda that corrects the
	// sequence lock functionality needed for Lightning Network (among other
	// uses) defined by DCP0004.
	VoteIDFixLNSeqLocks = "fixlnseqlocks"
)

Variables

View Source
var BlockOneLedgerMainNet = []*TokenPayout{}/* 3146 elements not displayed */

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

View Source
var BlockOneLedgerRegNet = []*TokenPayout{
	{"RsKrWb7Vny1jnzL1sDLgKTAteh9RZcRr5g6", 100000 * 1e8},
	{"Rs8ca5cDALtsMVD4PV3xvFTC7dmuU1juvLv", 100000 * 1e8},
	{"RsHzbGt6YajuHpurtpqXXHz57LmYZK8w9tX", 100000 * 1e8},
}

BlockOneLedgerRegNet is the block one output ledger for the regression test network. See "Utopia organization related parameters" in regnetparams.go for information on how to spend these outputs.

View Source
var BlockOneLedgerSimNet = []*TokenPayout{
	{"SCiaSErr5pS11tSK1RN1n7tnJfetUK7ZLkh", 300000 * 1e8},
}

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

View Source
var BlockOneLedgerTestNet3 = []*TokenPayout{
	{"Tsi6gGYNSMmFwi7JoL5Li39SrERZTTMu6vY", 80000 * 1e8},
	{"TscB7V5RuR1oXpA364DFEsNDuAs8Rk6BHJE", 20000 * 1e8},
}

BlockOneLedgerTestNet3 is the block one output ledger for testnet version 3.

Functions

This section is empty.

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 Choice

type Choice struct {
	// Single unique word identifying vote (e.g. yes)
	Id string

	// Longer description of the vote.
	Description string

	// Bits used for this vote.
	Bits uint16

	// This is the abstain choice.  By convention this must be the 0 vote
	// (abstain) and exist only once in the Vote.Choices array.
	IsAbstain bool

	// This coince indicates a hard No Vote.  By convention this must exist
	// only once in the Vote.Choices array.
	IsNo bool
}

Choice defines one of the possible Choices that make up a vote. The 0 value in Bits indicates the default choice. Care should be taken not to bias a vote with the default choice.

type ConsensusDeployment

type ConsensusDeployment struct {
	// Vote describes the what is being voted on and what the choices are.
	// This is sitting in a struct in order to make merging between btcd
	// easier.
	Vote Vote

	// StartTime is the median block time after which voting on the
	// deployment starts.
	StartTime uint64

	// ExpireTime is the median block time after which the attempted
	// deployment expires.
	ExpireTime uint64
}

ConsensusDeployment defines details related to a specific consensus rule change that is voted in. This is part of BIP0009.

type DNSSeed

type DNSSeed struct {
	// Host defines the hostname of the seed.
	Host string

	// HasFiltering defines whether the seed supports filtering
	// by service flags (wire.ServiceFlag).
	HasFiltering bool
}

DNSSeed identifies a DNS seed.

func (DNSSeed) String

func (d DNSSeed) String() string

String returns the hostname of the DNS seed in human-readable form.

type Params

type Params struct {
	// Name defines a human-readable identifier for the network.
	Name string

	// Net defines the magic bytes used to identify the network.
	Net wire.CurrencyNet

	// DefaultPort defines the default peer-to-peer port for the network.
	DefaultPort string

	// DNSSeeds defines a list of DNS seeds for the network that are used
	// as one method to discover peers.
	DNSSeeds []DNSSeed

	// GenesisBlock defines the first block of the chain.
	GenesisBlock *wire.MsgBlock

	// GenesisHash is the starting block hash.
	GenesisHash chainhash.Hash

	// PowLimit defines the highest allowed proof of work value for a block
	// as a uint256.
	PowLimit *big.Int

	// PowLimitBits defines the highest allowed proof of work value for a
	// block in compact form.
	PowLimitBits uint32

	// ReduceMinDifficulty defines whether the network should reduce the
	// minimum required difficulty after a long enough period of time has
	// passed without finding a block.  This is really only useful for test
	// networks and should not be set on a main network.
	ReduceMinDifficulty bool

	// MinDiffReductionTime is the amount of time after which the minimum
	// required difficulty should be reduced when a block hasn't been found.
	//
	// NOTE: This only applies if ReduceMinDifficulty is true.
	MinDiffReductionTime time.Duration

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

	// MaximumBlockSizes are the maximum sizes of a block that can be
	// generated on the network.  It is an array because the max block size
	// can be different values depending on the results of a voting agenda.
	// The first entry is the initial block size for the network, while the
	// other entries are potential block size changes which take effect when
	// the vote for the associated agenda succeeds.
	MaximumBlockSizes []int

	// MaxTxSize is the maximum number of bytes a serialized transaction can
	// be in order to be considered valid by consensus.
	MaxTxSize int

	// TargetTimePerBlock is the desired amount of time to generate each
	// block.
	TargetTimePerBlock 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 the 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

	// SubsidyReductionInterval is the reduction interval in blocks.
	SubsidyReductionInterval 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

	// These fields are related to voting on consensus rule changes as
	// defined by BIP0009.
	//
	// RuleChangeActivationQurom is the number of votes required for a vote
	// to take effect.
	//
	// RuleChangeActivationInterval is the number of blocks in each threshold
	// state retarget window.
	//
	// Deployments define the specific consensus rule changes to be voted
	// on for the stake version (the map key).
	RuleChangeActivationQuorum     uint32
	RuleChangeActivationMultiplier uint32
	RuleChangeActivationDivisor    uint32
	RuleChangeActivationInterval   uint32
	Deployments                    map[uint32][]ConsensusDeployment

	// Enforce current block version once network has upgraded.
	BlockEnforceNumRequired uint64

	// Reject previous block versions once network has upgraded.
	BlockRejectNumRequired uint64

	// The number of nodes to check.
	BlockUpgradeNumToCheck uint64

	// AcceptNonStdTxs is a mempool param to either accept and relay
	// non standard txs to the network or reject them
	AcceptNonStdTxs 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

	// SLIP-0044 registered coin type used for BIP44, used in the hierarchical
	// deterministic path for address generation.
	// All SLIP-0044 registered coin types are are defined here:
	// https://github.com/satoshilabs/slips/blob/master/slip-0044.md
	SLIP0044CoinType uint32

	// Legacy BIP44 coin type used in the hierarchical deterministic path for
	// address generation. Previous name was HDCoinType, the LegacyCoinType
	// was introduced for backwards compatibility. Usually, SLIP0044CoinType
	// should be used instead.
	LegacyCoinType uint32

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

	// Ticket pool sizes for Utopia 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 Utopia 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

	// CoinbaseMaturity is the number of blocks required before newly mined
	// coins (coinbase transactions) can be spent.
	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

	// StakeVersionInterval determines the interval where the stake version
	// is calculated.
	StakeVersionInterval 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

	// StakeMajorityMultiplier and StakeMajorityDivisor are used
	// to calculate the super majority of stake votes using integer math as
	// such: X*StakeMajorityMultiplier/StakeMajorityDivisor
	StakeMajorityMultiplier int32
	StakeMajorityDivisor    int32

	// OrganizationPkScript is the output script for block taxes to be
	// distributed to in every block's coinbase. It should ideally be a P2SH
	// multisignature address.  OrganizationPkScriptVersion is the version
	// of the output script.  Until PoS hardforking is implemented, this
	// version must always match for a block to validate.
	OrganizationPkScript        []byte
	OrganizationPkScriptVersion uint16

	// 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 Utopia network by its parameters. These parameters may be used by Utopia applications to differentiate networks as well as addresses and keys for one network from those intended for use on another network.

func MainNetParams

func MainNetParams() *Params

MainNetParams returns the network parameters for the main Utopia network.

func RegNetParams

func RegNetParams() *Params

RegNetParams returns the network parameters for the regression test network. This should not be confused with the public test network or the simulation test network. The purpose of this network is primarily for unit tests and RPC server tests. On the other hand, the simulation test network is intended for full integration tests between different applications such as wallets, voting service providers, mining pools, block explorers, and other services that build on Utopia.

Since this network is only intended for unit testing, its values are subject to change even if it would cause a hard fork.

func SimNetParams

func SimNetParams() *Params

SimNetParams returns the network parameters for the simulation test 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 and full integration tests between different applications such as wallets, voting service providers, mining pools, block explorers, and other services that build on Utopia.

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.

func TestNet3Params

func TestNet3Params() *Params

TestNet3Params return the network parameters for the test currency network. This network is sometimes simply called "testnet". This is the third public iteration of testnet.

func (*Params) AddrIDPubKeyHashECDSAV0

func (p *Params) AddrIDPubKeyHashECDSAV0() [2]byte

AddrIDPubKeyHashECDSAV0 returns the magic prefix bytes for version 0 pay-to-pubkey-hash addresses where the underlying pubkey is secp256k1 and the signature algorithm is ECDSA.

func (*Params) AddrIDPubKeyHashEd25519V0

func (p *Params) AddrIDPubKeyHashEd25519V0() [2]byte

AddrIDPubKeyHashEd25519V0 returns the magic prefix bytes for version 0 pay-to-pubkey-hash addresses where the underlying pubkey and signature algorithm are Ed25519.

func (*Params) AddrIDPubKeyHashSchnorrV0

func (p *Params) AddrIDPubKeyHashSchnorrV0() [2]byte

AddrIDPubKeyHashSchnorrV0 returns the magic prefix bytes for version 0 pay-to-pubkey-hash addresses where the underlying pubkey is secp256k1 and the signature algorithm is Schnorr.

func (*Params) AddrIDPubKeyV0

func (p *Params) AddrIDPubKeyV0() [2]byte

AddrIDPubKeyV0 returns the magic prefix bytes for version 0 pay-to-pubkey addresses.

func (*Params) AddrIDScriptHashV0

func (p *Params) AddrIDScriptHashV0() [2]byte

AddrIDScriptHashV0 returns the magic prefix bytes for version 0 pay-to-script-hash addresses.

func (*Params) BlockOneSubsidy

func (p *Params) BlockOneSubsidy() int64

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

func (*Params) HDPrivKeyVersion

func (p *Params) HDPrivKeyVersion() [4]byte

HDPrivKeyVersion returns the hierarchical deterministic extended private key magic version bytes for the network the parameters define.

func (*Params) HDPubKeyVersion

func (p *Params) HDPubKeyVersion() [4]byte

HDPubKeyVersion returns the hierarchical deterministic extended public key magic version bytes for the network the parameters define.

func (*Params) LatestCheckpointHeight

func (p *Params) LatestCheckpointHeight() int64

LatestCheckpointHeight is the height of the latest checkpoint block in the parameters.

func (*Params) StakeEnableHeight

func (p *Params) StakeEnableHeight() int64

StakeEnableHeight returns the height at which the first ticket could possibly mature.

func (*Params) StakeValidationBeginHeight

func (p *Params) StakeValidationBeginHeight() int64

StakeValidationBeginHeight returns the height at which votes become required to extend a block. This height is the first that will be voted on, but will not include any votes itself.

func (*Params) TicketExpiryBlocks

func (p *Params) TicketExpiryBlocks() uint32

TicketExpiryBlocks returns the number of blocks after maturity that tickets expire. This will be >= (StakeEnableHeight() + StakeValidationBeginHeight()).

func (*Params) TotalSubsidyProportions

func (p *Params) TotalSubsidyProportions() uint16

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

func (*Params) VotesPerBlock

func (p *Params) VotesPerBlock() uint16

VotesPerBlock returns the maximum number of votes a block must contain to receive full subsidy.

type TokenPayout

type TokenPayout struct {
	Address string
	Amount  int64
}

TokenPayout is a payout for block 1 which specifies a required script version, script, and amount to pay in a transaction output.

type Vote

type Vote struct {
	// Single unique word identifying the vote.
	Id string

	// Longer description of what the vote is about.
	Description string

	// Usable bits for this vote.
	Mask uint16

	Choices []Choice
}

Vote describes a voting instance. It is self-describing so that the UI can be directly implemented using the fields. Mask determines which bits can be used. Bits are enumerated and must be consecutive. Each vote requires one and only one abstain (bits = 0) and reject vote (IsNo = true).

For example, change block height from int64 to uint64.

Vote {
	Id:          "blockheight",
	Description: "Change block height from int64 to uint64"
	Mask:        0x0006,
	Choices:     []Choice{
		{
			Id:          "abstain",
			Description: "abstain voting for change",
			Bits:        0x0000,
			IsAbstain:   true,
			IsNo:        false,
		},
		{
			Id:          "no",
			Description: "reject changing block height to uint64",
			Bits:        0x0002,
			IsAbstain:   false,
			IsNo:        false,
		},
		{
			Id:          "yes",
			Description: "accept changing block height to uint64",
			Bits:        0x0004,
			IsAbstain:   false,
			IsNo:        true,
		},
	},
}

func (*Vote) VoteIndex

func (v *Vote) VoteIndex(vote uint16) int

VoteIndex compares vote to Choice.Bits and returns the index into the Choices array. If the vote is invalid it returns -1.

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 provides abstracted hash functionality.
Package chainhash provides abstracted hash functionality.

Jump to

Keyboard shortcuts

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