dcrutil

package module
v4.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2021 License: ISC Imports: 23 Imported by: 224

README

dcrutil

Build Status ISC License Doc

Package dcrutil provides decred-specific convenience functions and types. A comprehensive suite of tests is provided to ensure proper functionality.

This package was developed for dcrd, a full-node implementation of Decred which is under active development by Company 0. Although it was primarily written for dcrd, this package has intentionally been designed so it can be used as a standalone package for any projects needing the functionality provided.

Installation and Updating

This package is part of the github.com/decred/dcrd/dcrutil/v3 module. Use the standard go tooling for working with modules to incorporate it.

License

Package dcrutil is licensed under the copyfree ISC License.

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

Examples

Constants

View Source
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.

View Source
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
)
View Source
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.

View Source
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

View Source
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

func AppDataDir(appName string, roaming bool) string

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 Hash160

func Hash160(buf []byte) []byte

Hash160 calculates the hash ripemd160(hash256(b)).

func IsFlagSet16

func IsFlagSet16(flags uint16, flag uint16) bool

IsFlagSet16 returns true/false for a flag at flag field 'flag'.

func SetFlag16

func SetFlag16(flags *uint16, flag uint16, b bool)

SetFlag16 sets a bit flag at flag position 'flag' to bool 'b'.

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

func NewAmount(f float64) (Amount, error)

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

func (a Amount) MulF64(f float64) Amount

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) String

func (a Amount) String() string

String is the equivalent of calling Format with AmountCoin.

func (Amount) ToCoin

func (a Amount) ToCoin() float64

ToCoin is the equivalent of calling ToUnit with AmountCoin.

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

func NewBlock(msgBlock *wire.MsgBlock) *Block

NewBlock returns a new instance of a block given an underlying wire.MsgBlock. See Block.

func NewBlockDeepCopy

func NewBlockDeepCopy(msgBlock *wire.MsgBlock) *Block

NewBlockDeepCopy deep copies an entire block down to the wire components and returns the new block based off of this copy.

func NewBlockDeepCopyCoinbase

func NewBlockDeepCopyCoinbase(msgBlock *wire.MsgBlock) *Block

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

func NewBlockFromBlockAndBytes(msgBlock *wire.MsgBlock, serializedBlock []byte) *Block

NewBlockFromBlockAndBytes returns a new instance of a block given an underlying wire.MsgBlock and the serialized bytes for it. See Block.

func NewBlockFromBytes

func NewBlockFromBytes(serializedBlock []byte) (*Block, error)

NewBlockFromBytes returns a new instance of a block given the serialized bytes. See Block.

func NewBlockFromReader

func NewBlockFromReader(r io.Reader) (*Block, error)

NewBlockFromReader returns a new instance of a block given a Reader to deserialize the block. See Block.

func (*Block) BlockHeaderBytes

func (b *Block) BlockHeaderBytes() ([]byte, error)

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

func (b *Block) Bytes() ([]byte, error)

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

func (b *Block) Hash() *chainhash.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

func (b *Block) Height() int64

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) MsgBlock

func (b *Block) MsgBlock() *wire.MsgBlock

MsgBlock returns the underlying wire.MsgBlock for the Block.

func (*Block) STransactions

func (b *Block) STransactions() []*Tx

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

func (b *Block) STx(txNum int) (*Tx, error)

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

func (b *Block) STxHash(txNum int) (*chainhash.Hash, error)

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

func (b *Block) Transactions() []*Tx

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

func (b *Block) Tx(txNum int) (*Tx, error)

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

func (b *Block) TxHash(txNum int) (*chainhash.Hash, error)

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.

func (*Block) TxLoc

func (b *Block) TxLoc() ([]wire.TxLoc, []wire.TxLoc, error)

TxLoc returns the offsets and lengths of each transaction in a raw block. It is used to allow fast indexing into transactions within the raw byte stream.

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 NewTx

func NewTx(msgTx *wire.MsgTx) *Tx

NewTx returns a new instance of a transaction given an underlying wire.MsgTx. See Tx.

func NewTxDeep

func NewTxDeep(msgTx *wire.MsgTx) *Tx

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

func NewTxDeepTxIns(tx *Tx) *Tx

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

func NewTxFromBytes(serializedTx []byte) (*Tx, error)

NewTxFromBytes returns a new instance of a transaction given the serialized bytes. See Tx.

func NewTxFromReader

func NewTxFromReader(r io.Reader) (*Tx, error)

NewTxFromReader returns a new instance of a transaction given a Reader to deserialize the transaction. See Tx.

func (*Tx) Hash

func (t *Tx) Hash() *chainhash.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

func (t *Tx) Index() int

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) MsgTx

func (t *Tx) MsgTx() *wire.MsgTx

MsgTx returns the underlying wire.MsgTx for the transaction.

func (*Tx) SetIndex

func (t *Tx) SetIndex(index int)

SetIndex sets the index of the transaction in within a block.

func (*Tx) SetTree

func (t *Tx) SetTree(tree int8)

SetTree sets the tree of the transaction in within a block.

func (*Tx) SetVersion

func (t *Tx) SetVersion(version uint16)

SetVersion sets the version of the transaction within a block.

func (*Tx) Tree

func (t *Tx) Tree() int8

Tree returns the saved tree of the transaction within a block. This value will be TxTreeUnknown if it hasn't already explicitly been set.

func (*Tx) Version

func (t *Tx) Version() uint16

Version returns the transaction version.

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

func DecodeWIF(wif string, net [2]byte) (*WIF, error)

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

func NewWIF(privKey []byte, net [2]byte, scheme dcrec.SignatureType) (*WIF, error)

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

func (w *WIF) PrivKey() []byte

PrivKey returns the serialized private key described by the WIF. The bytes must not be modified.

func (*WIF) PubKey

func (w *WIF) PubKey() []byte

PubKey returns the compressed serialization of the associated public key for the WIF's private key.

func (*WIF) String

func (w *WIF) String() string

String creates the Wallet Import Format string encoding of a WIF structure. See DecodeWIF for a detailed breakdown of the format and requirements of a valid WIF string.

Directories

Path Synopsis
Package txsort provides stable transaction sorting.
Package txsort provides stable transaction sorting.

Jump to

Keyboard shortcuts

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