Documentation ¶
Overview ¶
Package dcrutil provides decred-specific convenience functions and types.
Block Overview ¶
A Block defines a Decred block that provides easier and more efficient manipulation of raw wire protocol blocks. It also memoizes hashes for the block and its transactions on their first access so subsequent accesses don't have to repeat the relatively expensive hashing operations.
Tx Overview ¶
A Tx defines a Decred transaction that provides more efficient manipulation of raw wire protocol transactions. It memoizes the hash for the transaction on its first access so subsequent accesses don't have to repeat the relatively expensive hashing operations.
Address Overview ¶
The Address interface provides an abstraction for a Decred address. While the most common type is a pay-to-pubkey-hash, Decred already supports others and may well support more in the future. This package currently provides implementations for the pay-to-pubkey, pay-to-pubkey-hash, and pay-to-script-hash address types.
Index ¶
- Constants
- Variables
- func AppDataDir(appName string, roaming bool) string
- func Hash160(buf []byte) []byte
- func IsFlagSet16(flags uint16, flag uint16) bool
- func SetFlag16(flags *uint16, flag uint16, b bool)
- func VerifyMessage(address string, signature string, message string, params AddressParams) error
- type AddressParams
- type Amount
- type AmountSorter
- type AmountUnit
- type Block
- func NewBlock(msgBlock *wire.MsgBlock) *Block
- func NewBlockDeepCopy(msgBlock *wire.MsgBlock) *Block
- func NewBlockDeepCopyCoinbase(msgBlock *wire.MsgBlock) *Block
- func NewBlockFromBlockAndBytes(msgBlock *wire.MsgBlock, serializedBlock []byte) *Block
- func NewBlockFromBytes(serializedBlock []byte) (*Block, error)
- func NewBlockFromReader(r io.Reader) (*Block, error)
- func (b *Block) BlockHeaderBytes() ([]byte, error)
- func (b *Block) Bytes() ([]byte, error)
- func (b *Block) Hash() *chainhash.Hash
- func (b *Block) Height() int64
- func (b *Block) MsgBlock() *wire.MsgBlock
- func (b *Block) STransactions() []*Tx
- func (b *Block) STx(txNum int) (*Tx, error)
- func (b *Block) STxHash(txNum int) (*chainhash.Hash, error)
- func (b *Block) Transactions() []*Tx
- func (b *Block) Tx(txNum int) (*Tx, error)
- func (b *Block) TxHash(txNum int) (*chainhash.Hash, error)
- func (b *Block) TxLoc() ([]wire.TxLoc, []wire.TxLoc, error)
- type BoolArray16
- type ErrWrongWIFNetwork
- type Flags16
- type OutOfRangeError
- type Tx
- type WIF
Examples ¶
Constants ¶
const ( FlagNone Flags16 = 0 BlockValid = 1 << 0 // Describes whether TxTreeRegular is valid Flag01 = 1 << 1 Flag02 = 1 << 2 Flag03 = 1 << 3 Flag04 = 1 << 4 Flag05 = 1 << 5 Flag06 = 1 << 6 Flag07 = 1 << 7 Flag08 = 1 << 8 Flag09 = 1 << 9 Flag10 = 1 << 10 Flag11 = 1 << 11 Flag12 = 1 << 12 Flag13 = 1 << 13 Flag14 = 1 << 14 Flag15 = 1 << 15 )
Flag fields for uint16.
const ( // AtomsPerCent is the number of atomic units in one coin cent. AtomsPerCent = 1e6 // AtomsPerCoin is the number of atomic units in one coin. AtomsPerCoin = 1e8 // MaxAmount is the maximum transaction amount allowed in atoms. // Decred - Changeme for release MaxAmount = 21e6 * AtomsPerCoin )
const BlockHeightUnknown = int64(-1)
BlockHeightUnknown is the value returned for a block height that is unknown. This is typically because the block has not been inserted into the main chain yet.
const TxIndexUnknown = -1
TxIndexUnknown is the value returned for a transaction index that is unknown. This is typically because the transaction has not been inserted into a block yet.
Variables ¶
var ( // ErrMalformedPrivateKey describes an error where a WIF-encoded private key // cannot be decoded due to being improperly formatted. This may occur if // the byte length is incorrect or an unexpected magic number was // encountered. ErrMalformedPrivateKey = errors.New("malformed private key") // ErrChecksumMismatch describes an error where decoding failed due to a bad // checksum. ErrChecksumMismatch = errors.New("checksum mismatch") )
Functions ¶
func AppDataDir ¶
AppDataDir returns an operating system specific directory to be used for storing application data for an application.
The appName parameter is the name of the application the data directory is being requested for. This function will prepend a period to the appName for POSIX style operating systems since that is standard practice. An empty appName or one with a single dot is treated as requesting the current directory so only "." will be returned. Further, the first character of appName will be made lowercase for POSIX style operating systems and uppercase for Mac and Windows since that is standard practice.
The roaming parameter only applies to Windows where it specifies the roaming application data profile (%APPDATA%) should be used instead of the local one (%LOCALAPPDATA%) that is used by default.
Example results:
dir := AppDataDir("myapp", false) POSIX (Linux/BSD): ~/.myapp Mac OS: $HOME/Library/Application Support/Myapp Windows: %LOCALAPPDATA%\Myapp Plan 9: $home/myapp
func IsFlagSet16 ¶
IsFlagSet16 returns true/false for a flag at flag field 'flag'.
func VerifyMessage ¶
func VerifyMessage(address string, signature string, message string, params AddressParams) error
VerifyMessage verifies that signature is a valid signature of message and was created using the secp256k1 private key for address.
Types ¶
type AddressParams ¶
type AddressParams interface { // AddrIDPubKeyV0 returns the magic prefix bytes for version 0 pay-to-pubkey // addresses. AddrIDPubKeyV0() [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. AddrIDPubKeyHashECDSAV0() [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. AddrIDPubKeyHashEd25519V0() [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. AddrIDPubKeyHashSchnorrV0() [2]byte // AddrIDScriptHashV0 returns the magic prefix bytes for version 0 // pay-to-script-hash addresses. AddrIDScriptHashV0() [2]byte }
AddressParams defines an interface that is used to provide the parameters required when encoding and decoding addresses. These values are typically well-defined and unique per network.
type Amount ¶
type Amount int64
Amount represents the base coin monetary unit (colloquially referred to as an `Atom'). A single Amount is equal to 1e-8 of a coin.
Example ¶
a := dcrutil.Amount(0) fmt.Println("Zero Atom:", a) a = dcrutil.Amount(1e8) fmt.Println("100,000,000 Atoms:", a) a = dcrutil.Amount(1e5) fmt.Println("100,000 Atoms:", a)
Output: Zero Atom: 0 DCR 100,000,000 Atoms: 1 DCR 100,000 Atoms: 0.001 DCR
Example (UnitConversions) ¶
amount := dcrutil.Amount(44433322211100) fmt.Println("Atom to kCoin:", amount.Format(dcrutil.AmountKiloCoin)) fmt.Println("Atom to Coin:", amount) fmt.Println("Atom to MilliCoin:", amount.Format(dcrutil.AmountMilliCoin)) fmt.Println("Atom to MicroCoin:", amount.Format(dcrutil.AmountMicroCoin)) fmt.Println("Atom to Atom:", amount.Format(dcrutil.AmountAtom))
Output: Atom to kCoin: 444.333222111 kDCR Atom to Coin: 444333.222111 DCR Atom to MilliCoin: 444333222.111 mDCR Atom to MicroCoin: 444333222111 μDCR Atom to Atom: 44433322211100 Atom
func NewAmount ¶
NewAmount creates an Amount from a floating point value representing some value in the currency. NewAmount errors if f is NaN or +-Infinity, but does not check that the amount is within the total amount of coins producible as f may not refer to an amount at a single moment in time.
NewAmount is for specifically for converting DCR to Atoms (atomic units). For creating a new Amount with an int64 value which denotes a quantity of Atoms, do a simple type conversion from type int64 to Amount.
Example ¶
amountOne, err := dcrutil.NewAmount(1) if err != nil { fmt.Println(err) return } fmt.Println(amountOne) //Output 1 amountFraction, err := dcrutil.NewAmount(0.01234567) if err != nil { fmt.Println(err) return } fmt.Println(amountFraction) //Output 2 amountZero, err := dcrutil.NewAmount(0) if err != nil { fmt.Println(err) return } fmt.Println(amountZero) //Output 3 amountNaN, err := dcrutil.NewAmount(math.NaN()) if err != nil { fmt.Println(err) return } fmt.Println(amountNaN) //Output 4
Output: 1 DCR 0.01234567 DCR 0 DCR invalid coin amount
func (Amount) Format ¶
func (a Amount) Format(u AmountUnit) string
Format formats a monetary amount counted in coin base units as a string for a given unit. The conversion will succeed for any unit, however, known units will be formatted with an appended label describing the units with SI notation, or "atom" for the base unit.
func (Amount) MulF64 ¶
MulF64 multiplies an Amount by a floating point value. While this is not an operation that must typically be done by a full node or wallet, it is useful for services that build on top of Decred (for example, calculating a fee by multiplying by a percentage).
func (Amount) ToUnit ¶
func (a Amount) ToUnit(u AmountUnit) float64
ToUnit converts a monetary amount counted in coin base units to a floating point value representing an amount of coins.
type AmountSorter ¶
type AmountSorter []Amount
AmountSorter implements sort.Interface to allow a slice of Amounts to be sorted.
func (AmountSorter) Len ¶
func (s AmountSorter) Len() int
Len returns the number of Amounts in the slice. It is part of the sort.Interface implementation.
func (AmountSorter) Less ¶
func (s AmountSorter) Less(i, j int) bool
Less returns whether the Amount with index i should sort before the Amount with index j. It is part of the sort.Interface implementation.
func (AmountSorter) Swap ¶
func (s AmountSorter) Swap(i, j int)
Swap swaps the Amounts at the passed indices. It is part of the sort.Interface implementation.
type AmountUnit ¶
type AmountUnit int
AmountUnit describes a method of converting an Amount to something other than the base unit of a coin. The value of the AmountUnit is the exponent component of the decadic multiple to convert from an amount in coins to an amount counted in atomic units.
const ( AmountMegaCoin AmountUnit = 6 AmountKiloCoin AmountUnit = 3 AmountCoin AmountUnit = 0 AmountMilliCoin AmountUnit = -3 AmountMicroCoin AmountUnit = -6 AmountAtom AmountUnit = -8 )
These constants define various units used when describing a coin monetary amount.
func (AmountUnit) String ¶
func (u AmountUnit) String() string
String returns the unit as a string. For recognized units, the SI prefix is used, or "Atom" for the base unit. For all unrecognized units, "1eN DCR" is returned, where N is the AmountUnit.
type Block ¶
type Block struct {
// contains filtered or unexported fields
}
Block defines a cryptocurrency block that provides easier and more efficient manipulation of raw blocks. It also memoizes hashes for the block and its transactions on their first access so subsequent accesses don't have to repeat the relatively expensive hashing operations.
func NewBlock ¶
NewBlock returns a new instance of a block given an underlying wire.MsgBlock. See Block.
func NewBlockDeepCopy ¶
NewBlockDeepCopy deep copies an entire block down to the wire components and returns the new block based off of this copy.
func NewBlockDeepCopyCoinbase ¶
NewBlockDeepCopyCoinbase returns a new instance of a block given an underlying wire.MsgBlock, but makes a deep copy of the coinbase transaction since it's sometimes mutable.
func NewBlockFromBlockAndBytes ¶
NewBlockFromBlockAndBytes returns a new instance of a block given an underlying wire.MsgBlock and the serialized bytes for it. See Block.
func NewBlockFromBytes ¶
NewBlockFromBytes returns a new instance of a block given the serialized bytes. See Block.
func NewBlockFromReader ¶
NewBlockFromReader returns a new instance of a block given a Reader to deserialize the block. See Block.
func (*Block) BlockHeaderBytes ¶
BlockHeaderBytes returns the serialized bytes for the Block's header. This is equivalent to calling Serialize on the underlying wire.MsgBlock.Header, but it returns a byte slice.
func (*Block) Bytes ¶
Bytes returns the serialized bytes for the Block. This is equivalent to calling Serialize on the underlying wire.MsgBlock, however it caches the result so subsequent calls are more efficient.
func (*Block) Hash ¶
Hash returns the block identifier hash for the Block. This is equivalent to calling BlockHash on the underlying wire.MsgBlock, however it caches the result so subsequent calls are more efficient.
func (*Block) Height ¶
Height returns a casted int64 height from the block header.
This function should not be used for new code and will be removed in the future.
func (*Block) STransactions ¶
STransactions returns a slice of wrapped stake transactions (dcrutil.Tx) for all stake transactions in the Block. This is nearly equivalent to accessing the raw transactions (dcrwire.MsgTx) in the underlying wire.MsgBlock, however it instead provides easy access to wrapped versions (util.Tx) of them.
func (*Block) STx ¶
STx returns a wrapped transaction (dcrutil.Tx) for the stake transaction at the specified index in the Block. The supplied index is 0 based.
func (*Block) STxHash ¶
STxHash returns the hash for the requested stake transaction number in the Block. The supplied index is 0 based. That is to say, the first transaction in the block is txNum 0. This is equivalent to calling TxHash on the underlying wire.MsgTx, however it caches the result so subsequent calls are more efficient.
func (*Block) Transactions ¶
Transactions returns a slice of wrapped transactions (dcrutil.Tx) for all transactions in the Block. This is nearly equivalent to accessing the raw transactions (wire.MsgTx) in the underlying wire.MsgBlock, however it instead provides easy access to wrapped versions (dcrutil.Tx) of them.
func (*Block) Tx ¶
Tx returns a wrapped transaction (dcrutil.Tx) for the transaction at the specified index in the Block. The supplied index is 0 based. That is to say, the first transaction in the block is txNum 0. This is nearly equivalent to accessing the raw transaction (wire.MsgTx) from the underlying wire.MsgBlock, however the wrapped transaction has some helpful properties such as caching the hash so subsequent calls are more efficient.
func (*Block) TxHash ¶
TxHash returns the hash for the requested transaction number in the Block. The supplied index is 0 based. That is to say, the first transaction in the block is txNum 0. This is equivalent to calling TxHash on the underlying wire.MsgTx, however it caches the result so subsequent calls are more efficient.
type BoolArray16 ¶
type BoolArray16 [16]bool
BoolArray16 is a bool array that is generated from a uint16 containing flags.
func GenerateBoolArray16 ¶
func GenerateBoolArray16(flags uint16) BoolArray16
GenerateBoolArray16 generates a BoolArray16 from a uint16 containing flags.
type ErrWrongWIFNetwork ¶
type ErrWrongWIFNetwork [2]byte
ErrWrongWIFNetwork describes an error in which the provided WIF is not for the expected network.
func (ErrWrongWIFNetwork) Error ¶
func (e ErrWrongWIFNetwork) Error() string
Error implements the error interface.
type Flags16 ¶
type Flags16 uint16
Flags16 is the type for 2 bytes of flags; not really used except in the declaration below.
type OutOfRangeError ¶
type OutOfRangeError string
OutOfRangeError describes an error due to accessing an element that is out of range.
func (OutOfRangeError) Error ¶
func (e OutOfRangeError) Error() string
Error satisfies the error interface and prints human-readable errors.
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx defines a transaction that provides easier and more efficient manipulation of raw transactions. It also memoizes the hash for the transaction on its first access so subsequent accesses don't have to repeat the relatively expensive hashing operations.
func NewTxDeep ¶
NewTxDeep returns a new instance of a transaction given an underlying wire.MsgTx. Until NewTx, it completely copies the data in the msgTx so that there are new memory allocations, in case you were to somewhere else modify the data assigned to these pointers.
func NewTxDeepTxIns ¶
NewTxDeepTxIns is used to deep copy a transaction, maintaining the old pointers to the TxOuts while replacing the old pointers to the TxIns with deep copies. This is to prevent races when the fraud proofs for the transactions are set by the miner.
func NewTxFromBytes ¶
NewTxFromBytes returns a new instance of a transaction given the serialized bytes. See Tx.
func NewTxFromReader ¶
NewTxFromReader returns a new instance of a transaction given a Reader to deserialize the transaction. See Tx.
func (*Tx) Hash ¶
Hash returns the hash of the transaction. This is equivalent to calling TxHash on the underlying wire.MsgTx, however it caches the result so subsequent calls are more efficient.
func (*Tx) Index ¶
Index returns the saved index of the transaction within a block. This value will be TxIndexUnknown if it hasn't already explicitly been set.
func (*Tx) SetVersion ¶
SetVersion sets the version of the transaction within a block.
type WIF ¶
type WIF struct {
// contains filtered or unexported fields
}
WIF contains the individual components described by the Wallet Import Format (WIF). A WIF string is typically used to represent a private key and its associated address in a way that may be easily copied and imported into or exported from wallet software. WIF strings may be decoded into this structure by calling DecodeWIF or created with a user-provided private key by calling NewWIF.
func DecodeWIF ¶
DecodeWIF creates a new WIF structure by decoding the string encoding of the import format which is required to be for the provided network.
The WIF string must be a base58-encoded string of the following byte sequence:
- 2 bytes to identify the network
- 1 byte for ECDSA type
- 32 bytes of a binary-encoded, big-endian, zero-padded private key
- 4 bytes of checksum, must equal the first four bytes of the double SHA256 of every byte before the checksum in this sequence
If the base58-decoded byte sequence does not match this, DecodeWIF will return a non-nil error. ErrMalformedPrivateKey is returned when the WIF is of an impossible length. ErrChecksumMismatch is returned if the expected WIF checksum does not match the calculated checksum.
func NewWIF ¶
NewWIF creates a new WIF structure to export an address and its private key as a string encoded in the Wallet Import Format. The net parameter specifies the magic bytes of the network for which the WIF string is intended.
func (*WIF) DSA ¶
func (w *WIF) DSA() dcrec.SignatureType
DSA describes the signature scheme of the key.
func (*WIF) PrivKey ¶
PrivKey returns the serialized private key described by the WIF. The bytes must not be modified.