dcrutil

package module
v8.0.4 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2022 License: ISC Imports: 22 Imported by: 2

README

dcrutil

Build Status ISC License GoDoc

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

$ go get -u github.com/Decred-Next/dcrnd/dcrutil

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 (
	// ErrChecksumMismatch describes an error where decoding failed due
	// to a bad checksum.
	ErrChecksumMismatch = errors.New("checksum mismatch")

	// ErrUnknownAddressType describes an error where an address can not be
	// decoded as a specific address type due to the string encoding
	// beginning with unrecognized values that identify the network, type,
	// and signature algorithm.
	ErrUnknownAddressType = errors.New("unknown address type")
)
View Source
var ErrInvalidPubKeyFormat = errors.New("invalid pubkey format")

ErrInvalidPubKeyFormat indicates that a serialized pubkey is unusable as it is neither in the uncompressed or compressed format.

View Source
var ErrMalformedPrivateKey = errors.New("malformed private key")

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.

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'.

Types

type Address

type Address interface {
	// String returns the string encoding of the transaction output
	// destination.
	//
	// Please note that String differs subtly from Address: String will
	// return the value as a string without any conversion, while Address
	// may convert destination types (for example, converting pubkeys to
	// P2PKH addresses) before encoding as a payment address string.
	String() string

	// Address returns the string encoding of the payment address associated
	// with the Address value.  See the comment on String for how this
	// method differs from String.
	Address() string

	// ScriptAddress returns the raw bytes of the address to be used
	// when inserting the address into a txout's script.
	ScriptAddress() []byte

	// Hash160 returns the Hash160(data) where data is the data normally
	// hashed to 160 bits from the respective address type.
	Hash160() *[ripemd160.Size]byte
}

Address is an interface type for any type of destination a transaction output may spend to. This includes pay-to-pubkey (P2PK), pay-to-pubkey-hash (P2PKH), and pay-to-script-hash (P2SH). Address is designed to be generic enough that other kinds of addresses may be added in the future without changing the decoding and encoding API.

func DecodeAddress

func DecodeAddress(addr string, net AddressParams) (Address, error)

DecodeAddress decodes the string encoding of an address and returns the Address if it is a valid encoding for a known address type and is for the provided network.

Example

This example demonstrates decoding addresses, determining their underlying type, and displaying their associated underlying hash160 and digital signature algorithm.

// Ordinarily addresses would be read from the user or the result of a
// derivation, but they are hard coded here for the purposes of this
// example.
mainNetParmas := chaincfg.MainNetParams()
addrsToDecode := []string{
	"DsRUvfCwTMrKz29dDiQBJhZii9GDN3bVx6Q", // pay-to-pubkey-hash ecdsa
	"DSpf9Sru9MarMKQQnuzTiQ9tjWVJA3KSm2d", // pay-to-pubkey-hash schnorr
}
for idx, encodedAddr := range addrsToDecode {
	addr, err := dcrutil.DecodeAddress(encodedAddr, mainNetParmas)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("addr%d hash160: %x\n", idx, *addr.Hash160())

	// The example addresses are pay-to-pubkey-hash with different signature
	// algorithms, so this code is limited to that type
	switch a := addr.(type) {
	case *dcrutil.AddressPubKeyHash:
		// Determine and display the digital signature algorithm.
		algo := "unknown"
		switch a.DSA() {
		case dcrec.STEcdsaSecp256k1:
			algo = "ECDSA"
		case dcrec.STSchnorrSecp256k1:
			algo = "Schnorr"
		}
		fmt.Printf("addr%d DSA: %v\n", idx, algo)

	default:
		fmt.Println("Unexpected test address type")
		return
	}
}
Output:

addr0 hash160: 05ad744deacf5334671d3e62db86230af1891f71
addr0 DSA: ECDSA
addr1 hash160: e280cb6e66b96679aec288b1fbdbd4db08077a1b
addr1 DSA: Schnorr

func NewAddressPubKey

func NewAddressPubKey(decoded []byte, net AddressParams) (Address, error)

NewAddressPubKey returns a new Address. decoded must be 33 bytes.

type AddressEdwardsPubKey

type AddressEdwardsPubKey struct {
	// contains filtered or unexported fields
}

AddressEdwardsPubKey is an Address for an Ed25519 pay-to-pubkey transaction.

func NewAddressEdwardsPubKey

func NewAddressEdwardsPubKey(serializedPubKey []byte, net AddressParams) (*AddressEdwardsPubKey, error)

NewAddressEdwardsPubKey returns a new AddressEdwardsPubKey which represents a pay-to-pubkey address, using an Ed25519 pubkey. The serializedPubKey parameter must be a valid 32 byte serialized public key.

func (*AddressEdwardsPubKey) Address

func (a *AddressEdwardsPubKey) Address() string

Address returns the string encoding of the public key as a pay-to-pubkey-hash.

Part of the Address interface.

func (*AddressEdwardsPubKey) AddressPubKeyHash

func (a *AddressEdwardsPubKey) AddressPubKeyHash() *AddressPubKeyHash

AddressPubKeyHash returns the pay-to-pubkey address converted to a pay-to-pubkey-hash address.

func (*AddressEdwardsPubKey) DSA

func (a *AddressEdwardsPubKey) DSA() dcrec.SignatureType

DSA returns the underlying digital signature algorithm for the address.

func (*AddressEdwardsPubKey) Hash160

func (a *AddressEdwardsPubKey) Hash160() *[ripemd160.Size]byte

Hash160 returns the underlying array of the pubkey hash. This can be useful when an array is more appropriate than a slice (for example, when used as map keys).

func (*AddressEdwardsPubKey) PubKey

PubKey returns the underlying public key for the address.

func (*AddressEdwardsPubKey) ScriptAddress

func (a *AddressEdwardsPubKey) ScriptAddress() []byte

ScriptAddress returns the bytes to be included in a txout script to pay to a public key. Setting the public key format will affect the output of this function accordingly. Part of the Address interface.

func (*AddressEdwardsPubKey) String

func (a *AddressEdwardsPubKey) String() string

String returns the hex-encoded human-readable string for the pay-to-pubkey address. This is not the same as calling Address.

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 AddressPubKeyHash

type AddressPubKeyHash struct {
	// contains filtered or unexported fields
}

AddressPubKeyHash is an Address for a pay-to-pubkey-hash (P2PKH) transaction.

func NewAddressPubKeyHash

func NewAddressPubKeyHash(pkHash []byte, net AddressParams, algo dcrec.SignatureType) (*AddressPubKeyHash, error)

NewAddressPubKeyHash returns a new AddressPubKeyHash. pkHash must be 20 bytes.

func (*AddressPubKeyHash) Address

func (a *AddressPubKeyHash) Address() string

Address returns the string encoding of a pay-to-pubkey-hash address.

Part of the Address interface.

func (*AddressPubKeyHash) DSA

func (a *AddressPubKeyHash) DSA() dcrec.SignatureType

DSA returns the digital signature algorithm for the associated public key hash.

func (*AddressPubKeyHash) Hash160

func (a *AddressPubKeyHash) Hash160() *[ripemd160.Size]byte

Hash160 returns the underlying array of the pubkey hash. This can be useful when an array is more appropriate than a slice (for example, when used as map keys).

func (*AddressPubKeyHash) ScriptAddress

func (a *AddressPubKeyHash) ScriptAddress() []byte

ScriptAddress returns the bytes to be included in a txout script to pay to a pubkey hash. Part of the Address interface.

func (*AddressPubKeyHash) String

func (a *AddressPubKeyHash) String() string

String returns a human-readable string for the pay-to-pubkey-hash address. This is equivalent to calling Address, but is provided so the type can be used as a fmt.Stringer.

type AddressScriptHash

type AddressScriptHash struct {
	// contains filtered or unexported fields
}

AddressScriptHash is an Address for a pay-to-script-hash (P2SH) transaction.

func NewAddressScriptHash

func NewAddressScriptHash(serializedScript []byte, net AddressParams) (*AddressScriptHash, error)

NewAddressScriptHash returns a new AddressScriptHash.

func NewAddressScriptHashFromHash

func NewAddressScriptHashFromHash(scriptHash []byte, net AddressParams) (*AddressScriptHash, error)

NewAddressScriptHashFromHash returns a new AddressScriptHash. scriptHash must be 20 bytes.

func (*AddressScriptHash) Address

func (a *AddressScriptHash) Address() string

Address returns the string encoding of a pay-to-script-hash address.

Part of the Address interface.

func (*AddressScriptHash) Hash160

func (a *AddressScriptHash) Hash160() *[ripemd160.Size]byte

Hash160 returns the underlying array of the script hash. This can be useful when an array is more appropriate than a slice (for example, when used as map keys).

func (*AddressScriptHash) ScriptAddress

func (a *AddressScriptHash) ScriptAddress() []byte

ScriptAddress returns the bytes to be included in a txout script to pay to a script hash. Part of the Address interface.

func (*AddressScriptHash) String

func (a *AddressScriptHash) String() string

String returns a human-readable string for the pay-to-script-hash address. This is equivalent to calling Address, but is provided so the type can be used as a fmt.Stringer.

type AddressSecSchnorrPubKey

type AddressSecSchnorrPubKey struct {
	// contains filtered or unexported fields
}

AddressSecSchnorrPubKey is an Address for a secp256k1 pay-to-pubkey transaction.

func NewAddressSecSchnorrPubKey

func NewAddressSecSchnorrPubKey(serializedPubKey []byte, net AddressParams) (*AddressSecSchnorrPubKey, error)

NewAddressSecSchnorrPubKey returns a new AddressSecpPubKey which represents a pay-to-pubkey address, using a secp256k1 pubkey. The serializedPubKey parameter must be a valid pubkey and must be compressed.

func (*AddressSecSchnorrPubKey) Address

func (a *AddressSecSchnorrPubKey) Address() string

Address returns the string encoding of the public key as a pay-to-pubkey-hash. Note that the public key format (uncompressed, compressed, etc) will change the resulting address. This is expected since pay-to-pubkey-hash is a hash of the serialized public key which obviously differs with the format. At the time of this writing, most Decred addresses are pay-to-pubkey-hash constructed from the compressed public key.

Part of the Address interface.

func (*AddressSecSchnorrPubKey) AddressPubKeyHash

func (a *AddressSecSchnorrPubKey) AddressPubKeyHash() *AddressPubKeyHash

AddressPubKeyHash returns the pay-to-pubkey address converted to a pay-to-pubkey-hash address.

func (*AddressSecSchnorrPubKey) DSA

func (a *AddressSecSchnorrPubKey) DSA() dcrec.SignatureType

DSA returns the underlying digital signature algorithm for the address.

func (*AddressSecSchnorrPubKey) Hash160

func (a *AddressSecSchnorrPubKey) Hash160() *[ripemd160.Size]byte

Hash160 returns the underlying array of the pubkey hash. This can be useful when an array is more appropriate than a slice (for example, when used as map keys).

func (*AddressSecSchnorrPubKey) ScriptAddress

func (a *AddressSecSchnorrPubKey) ScriptAddress() []byte

ScriptAddress returns the bytes to be included in a txout script to pay to a public key. Setting the public key format will affect the output of this function accordingly. Part of the Address interface.

func (*AddressSecSchnorrPubKey) String

func (a *AddressSecSchnorrPubKey) String() string

String returns the hex-encoded human-readable string for the pay-to-pubkey address. This is not the same as calling Address.

type AddressSecpPubKey

type AddressSecpPubKey struct {
	// contains filtered or unexported fields
}

AddressSecpPubKey is an Address for a secp256k1 pay-to-pubkey transaction.

func NewAddressSecpPubKey

func NewAddressSecpPubKey(serializedPubKey []byte, net AddressParams) (*AddressSecpPubKey, error)

NewAddressSecpPubKey returns a new AddressSecpPubKey which represents a pay-to-pubkey address, using a secp256k1 pubkey. The serializedPubKey parameter must be a valid pubkey and must be uncompressed or compressed.

func NewAddressSecpPubKeyCompressed

func NewAddressSecpPubKeyCompressed(pubkey chainec.PublicKey, params AddressParams) (*AddressSecpPubKey, error)

NewAddressSecpPubKeyCompressed creates a new address using a compressed public key

func (*AddressSecpPubKey) Address

func (a *AddressSecpPubKey) Address() string

Address returns the string encoding of the public key as a pay-to-pubkey-hash. Note that the public key format (uncompressed, compressed, etc) will change the resulting address. This is expected since pay-to-pubkey-hash is a hash of the serialized public key which obviously differs with the format. At the time of this writing, most Decred addresses are pay-to-pubkey-hash constructed from the compressed public key.

Part of the Address interface.

func (*AddressSecpPubKey) AddressPubKeyHash

func (a *AddressSecpPubKey) AddressPubKeyHash() *AddressPubKeyHash

AddressPubKeyHash returns the pay-to-pubkey address converted to a pay-to-pubkey-hash address. Note that the public key format (uncompressed, compressed, etc) will change the resulting address. This is expected since pay-to-pubkey-hash is a hash of the serialized public key which obviously differs with the format. At the time of this writing, most Decred addresses are pay-to-pubkey-hash constructed from the uncompressed public key.

func (*AddressSecpPubKey) DSA

func (a *AddressSecpPubKey) DSA() dcrec.SignatureType

DSA returns the underlying digital signature algorithm for the address.

func (*AddressSecpPubKey) Format

func (a *AddressSecpPubKey) Format() PubKeyFormat

Format returns the format (uncompressed, compressed, etc) of the pay-to-pubkey address.

func (*AddressSecpPubKey) Hash160

func (a *AddressSecpPubKey) Hash160() *[ripemd160.Size]byte

Hash160 returns the underlying array of the pubkey hash. This can be useful when an array is more appropriate than a slice (for example, when used as map keys).

func (*AddressSecpPubKey) PubKey

func (a *AddressSecpPubKey) PubKey() chainec.PublicKey

PubKey returns the underlying public key for the address.

func (*AddressSecpPubKey) ScriptAddress

func (a *AddressSecpPubKey) ScriptAddress() []byte

ScriptAddress returns the bytes to be included in a txout script to pay to a public key. Setting the public key format will affect the output of this function accordingly. Part of the Address interface.

func (*AddressSecpPubKey) String

func (a *AddressSecpPubKey) String() string

String returns the hex-encoded human-readable string for the pay-to-pubkey address. This is not the same as calling Address.

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. See GoDoc for example: https://godoc.org/github.com/Decred-Next/dcrnd/dcrutil#example-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 PubKeyFormat

type PubKeyFormat int

PubKeyFormat describes what format to use for a pay-to-pubkey address.

const (
	// PKFUncompressed indicates the pay-to-pubkey address format is an
	// uncompressed public key.
	PKFUncompressed PubKeyFormat = iota

	// PKFCompressed indicates the pay-to-pubkey address format is a
	// compressed public key.
	PKFCompressed
)

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(msgTx *wire.MsgTx) *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) 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.

type WIF

type WIF struct {

	// PrivKey is the private key being imported or exported.
	PrivKey chainec.PrivateKey
	// 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 chainec.PrivateKey, net [2]byte, ecType dcrec.SignatureType) *WIF

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 returns the ECDSA type for the private key.

func (*WIF) SerializePubKey

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

SerializePubKey serializes the associated public key of the imported or exported private key in compressed format. The serialization format chosen depends on the value of w.ecType.

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