dcrutil

package
v1.2.0-rc2 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2018 License: ISC Imports: 19 Imported by: 0

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/dcrd/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.

To decode/encode an address:

// NOTE: The default network is only used for address types which do not
// already contain that information.  At this time, that is only
// pay-to-pubkey addresses.
addrString := "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962" +
	"e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d57" +
	"8a4c702b6bf11d5f"
defaultNet := &chaincfg.MainNetParams
addr, err := dcrutil.DecodeAddress(addrString, defaultNet)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(addr.EncodeAddress())

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
	// decoded as a specific address type due to the string encoding
	// beginning with an identifier byte unknown to any standard or
	// registered (via chaincfg.Register) network.
	ErrUnknownAddressType = errors.New("unknown address type")

	// ErrAddressCollision describes an error where an address can not
	// be uniquely determined as either a pay-to-pubkey-hash or
	// pay-to-script-hash address since the leading identifier is used for
	// describing both address kinds, but for different networks.  Rather
	// than assuming or defaulting to one or the other, this error is
	// returned and the caller must decide how to decode the address.
	ErrAddressCollision = errors.New("address collision")

	// ErrMissingDefaultNet describes an error in DecodeAddress that
	// attempts to decode an address without defining which network to decode
	// for.
	ErrMissingDefaultNet = errors.New("default net not defined")
)
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 EncodeAddress: String
	// will return the value as a string without any conversion, while
	// EncodeAddress may convert destination types (for example,
	// converting pubkeys to P2PKH addresses) before encoding as a
	// payment address string.
	String() string

	// EncodeAddress 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.
	EncodeAddress() 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

	// IsForNet returns whether or not the address is associated with the
	// passed network.
	IsForNet(*chaincfg.Params) bool

	// DSA returns the digital signature algorithm for the address.
	DSA(*chaincfg.Params) int

	// Net returns the network parameters of the address.
	Net() *chaincfg.Params
}

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) (Address, error)

DecodeAddress decodes the string encoding of an address and returns the Address if addr is a valid encoding for a known address type

func NewAddressPubKey

func NewAddressPubKey(decoded []byte, net *chaincfg.Params) (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 *chaincfg.Params) (*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) 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(net *chaincfg.Params) int

DSA returns the underlying digital signature algorithm for the address.

func (*AddressEdwardsPubKey) EncodeAddress

func (a *AddressEdwardsPubKey) EncodeAddress() string

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

Part of the Address interface.

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

func (a *AddressEdwardsPubKey) IsForNet(net *chaincfg.Params) bool

IsForNet returns whether or not the pay-to-pubkey address is associated with the passed network.

func (*AddressEdwardsPubKey) Net

Net returns the network for the address.

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

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 *chaincfg.Params,
	algo int) (*AddressPubKeyHash, error)

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

func (*AddressPubKeyHash) DSA

func (a *AddressPubKeyHash) DSA(net *chaincfg.Params) int

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

func (*AddressPubKeyHash) EncodeAddress

func (a *AddressPubKeyHash) EncodeAddress() string

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

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

func (a *AddressPubKeyHash) IsForNet(net *chaincfg.Params) bool

IsForNet returns whether or not the pay-to-pubkey-hash address is associated with the passed network.

func (*AddressPubKeyHash) Net

func (a *AddressPubKeyHash) Net() *chaincfg.Params

Net returns the network for the address.

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 EncodeAddress, 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 *chaincfg.Params) (*AddressScriptHash, error)

NewAddressScriptHash returns a new AddressScriptHash.

func NewAddressScriptHashFromHash

func NewAddressScriptHashFromHash(scriptHash []byte,
	net *chaincfg.Params) (*AddressScriptHash, error)

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

func (*AddressScriptHash) DSA

func (a *AddressScriptHash) DSA(net *chaincfg.Params) int

DSA returns -1 (invalid) as the digital signature algorithm for scripts, as scripts may not involve digital signatures at all.

func (*AddressScriptHash) EncodeAddress

func (a *AddressScriptHash) EncodeAddress() string

EncodeAddress 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) IsForNet

func (a *AddressScriptHash) IsForNet(net *chaincfg.Params) bool

IsForNet returns whether or not the pay-to-script-hash address is associated with the passed network.

func (*AddressScriptHash) Net

func (a *AddressScriptHash) Net() *chaincfg.Params

Net returns the network for the address.

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 EncodeAddress, 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 *chaincfg.Params) (*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) AddressPubKeyHash

func (a *AddressSecSchnorrPubKey) AddressPubKeyHash() *AddressPubKeyHash

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

func (*AddressSecSchnorrPubKey) DSA

DSA returns the underlying digital signature algorithm for the address.

func (*AddressSecSchnorrPubKey) EncodeAddress

func (a *AddressSecSchnorrPubKey) EncodeAddress() string

EncodeAddress 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 uncompressed public key.

Part of the Address interface.

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

func (a *AddressSecSchnorrPubKey) IsForNet(net *chaincfg.Params) bool

IsForNet returns whether or not the pay-to-pubkey address is associated with the passed network.

func (*AddressSecSchnorrPubKey) Net

Net returns the network for the address.

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

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 *chaincfg.Params) (*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 *chaincfg.Params) (*AddressSecpPubKey, error)

NewAddressSecpPubKeyCompressed creates a new address using a compressed public key

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(net *chaincfg.Params) int

DSA returns the underlying digital signature algorithm for the address.

func (*AddressSecpPubKey) EncodeAddress

func (a *AddressSecpPubKey) EncodeAddress() string

EncodeAddress 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 uncompressed public key.

Part of the Address interface.

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

func (a *AddressSecpPubKey) IsForNet(net *chaincfg.Params) bool

IsForNet returns whether or not the pay-to-pubkey address is associated with the passed network.

func (*AddressSecpPubKey) Net

func (a *AddressSecpPubKey) Net() *chaincfg.Params

Net returns the network for the address.

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

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
package main

import (
	"fmt"

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

func main() {

	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)
package main

import (
	"fmt"

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

func main() {
	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: http://godoc.org/github.com/decred/dcrd/dcrutil#example-Amount

Example
package main

import (
	"fmt"
	"math"

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

func main() {
	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 formated 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, 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 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) (*WIF, error)

DecodeWIF creates a new WIF structure by decoding the string encoding of the import format.

The WIF string must be a base58-encoded string of the following byte sequence:

  • 2 bytes to identify the network, must be 0x80 for mainnet or 0xef for testnet
  • 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 *chaincfg.Params, ecType int) (*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 compress argument specifies whether the address intended to be imported or exported was created by serializing the public key compressed rather than uncompressed.

func (*WIF) DSA

func (w *WIF) DSA() int

DSA returns the ECDSA type for the private key.

func (*WIF) IsForNet

func (w *WIF) IsForNet(net *chaincfg.Params) bool

IsForNet returns whether or not the decoded WIF structure is associated with the passed network.

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