Documentation ¶
Overview ¶
Package util provides bitcoin-specific convenience functions and types.
Block Overview ¶
A Block defines a bitcoin 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 bitcoin 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 Bitcoin address. While the most common type is a pay-to-pubkey-hash, Bitcoin 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 := util.DecodeAddress(addrString, defaultNet) if err != nil { fmt.Println(err) return } fmt.Println(addr.EncodeAddress())
Index ¶
- Constants
- Variables
- func AppDataDir(appName string, roaming bool) string
- func BigToCompact(n *big.Int) uint32
- func CalcWork(bits uint32) *big.Int
- func CompactToBig(compact uint32) *big.Int
- func FastLog2Floor(n uint32) uint8
- func Hash160(buf []byte) []byte
- func NewTLSCertPair(organization string, validUntil time.Time, extraHosts []string) (cert, key []byte, err error)
- func ToCamelCase(str string) string
- type Address
- type AddressPubKey
- func (a *AddressPubKey) AddressPubKeyHash() *AddressPubKeyHash
- func (a *AddressPubKey) EncodeAddress() string
- func (a *AddressPubKey) Format() PubKeyFormat
- func (a *AddressPubKey) IsForPrefix(prefix Bech32Prefix) bool
- func (a *AddressPubKey) PubKey() *btcec.PublicKey
- func (a *AddressPubKey) ScriptAddress() []byte
- func (a *AddressPubKey) SetFormat(pkFormat PubKeyFormat)
- func (a *AddressPubKey) String() string
- type AddressPubKeyHash
- type AddressScriptHash
- type Amount
- type AmountUnit
- type Bech32Prefix
- type Block
- func (b *Block) Bytes() ([]byte, error)
- func (b *Block) CoinbaseTransaction() *Tx
- func (b *Block) FeeTransaction() *Tx
- func (b *Block) Hash() *daghash.Hash
- func (b *Block) Height() int32
- func (b *Block) IsGenesis() bool
- func (b *Block) MsgBlock() *wire.MsgBlock
- func (b *Block) SetHeight(height int32)
- func (b *Block) Transactions() []*Tx
- func (b *Block) Tx(txNum int) (*Tx, error)
- func (b *Block) TxHash(txNum int) (*daghash.Hash, error)
- func (b *Block) TxLoc() ([]wire.TxLoc, error)
- type OutOfRangeError
- type PubKeyFormat
- type Tx
- type WIF
Examples ¶
Constants ¶
const ( // 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. BlockHeightUnknown = int32(-1) // CoinbaseTransactionIndex is the index of the coinbase transaction in every block CoinbaseTransactionIndex = 0 // FeeTransactionIndex is the index of the fee transaction in every block (except genesis, // which doesn't have a fee transaction) FeeTransactionIndex = 1 )
const ( // SatoshiPerBitcent is the number of satoshi in one bitcoin cent. SatoshiPerBitcent = 1000000 // SatoshiPerBitcoin is the number of satoshi in one bitcoin (1 BTC). SatoshiPerBitcoin = 100000000 // MaxSatoshi is the maximum transaction amount allowed in satoshi. MaxSatoshi = 21000000 * SatoshiPerBitcoin )
const TxIndexUnknown = -1
TxIndexUnknown is the value returned for a transaction index that is unknown. This is typically because the transaction has not been inserted into a block yet.
Variables ¶
var ( // 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 // begining with an identifier byte unknown to any standard or // registered (via chaincfg.Register) network. ErrUnknownAddressType = errors.New("unknown address type") )
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 ¶
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 BigToCompact ¶
BigToCompact converts a whole number N to a compact representation using an unsigned 32-bit number. The compact representation only provides 23 bits of precision, so values larger than (2^23 - 1) only encode the most significant digits of the number. See CompactToBig for details.
Example ¶
This example demonstrates how to convert a target difficulty into the compact "bits" in a block header which represent that target difficulty .
package main import ( "fmt" "math/big" "github.com/daglabs/btcd/util" ) func main() { // Convert the target difficulty from block 300000 in the main block // chain to compact form. t := "0000000000000000896c00000000000000000000000000000000000000000000" targetDifficulty, success := new(big.Int).SetString(t, 16) if !success { fmt.Println("invalid target difficulty") return } bits := util.BigToCompact(targetDifficulty) fmt.Println(bits) }
Output: 419465580
func CalcWork ¶
CalcWork calculates a work value from difficulty bits. Bitcoin increases the difficulty for generating a block by decreasing the value which the generated hash must be less than. This difficulty target is stored in each block header using a compact representation as described in the documentation for CompactToBig. The main chain is selected by choosing the chain that has the most proof of work (highest difficulty). Since a lower target difficulty value equates to higher actual difficulty, the work value which will be accumulated must be the inverse of the difficulty. Also, in order to avoid potential division by zero and really small floating point numbers, the result adds 1 to the denominator and multiplies the numerator by 2^256.
func CompactToBig ¶
CompactToBig converts a compact representation of a whole number N to an unsigned 32-bit number. The representation is similar to IEEE754 floating point numbers.
Like IEEE754 floating point, there are three basic components: the sign, the exponent, and the mantissa. They are broken out as follows:
the most significant 8 bits represent the unsigned base 256 exponent
bit 23 (the 24th bit) represents the sign bit
the least significant 23 bits represent the mantissa
------------------------------------------------- | Exponent | Sign | Mantissa | ------------------------------------------------- | 8 bits [31-24] | 1 bit [23] | 23 bits [22-00] | -------------------------------------------------
The formula to calculate N is:
N = (-1^sign) * mantissa * 256^(exponent-3)
This compact form is only used in bitcoin to encode unsigned 256-bit numbers which represent difficulty targets, thus there really is not a need for a sign bit, but it is implemented here to stay consistent with bitcoind.
Example ¶
This example demonstrates how to convert the compact "bits" in a block header which represent the target difficulty to a big integer and display it using the typical hex notation.
package main import ( "fmt" "github.com/daglabs/btcd/util" ) func main() { // Convert the bits from block 300000 in the main block chain. bits := uint32(419465580) targetDifficulty := util.CompactToBig(bits) // Display it in hex. fmt.Printf("%064x\n", targetDifficulty.Bytes()) }
Output: 0000000000000000896c00000000000000000000000000000000000000000000
func FastLog2Floor ¶
FastLog2Floor calculates and returns floor(log2(x)) in a constant 5 steps.
func NewTLSCertPair ¶
func NewTLSCertPair(organization string, validUntil time.Time, extraHosts []string) (cert, key []byte, err error)
NewTLSCertPair returns a new PEM-encoded x.509 certificate pair based on a 521-bit ECDSA private key. The machine's local interface addresses and all variants of IPv4 and IPv6 localhost are included as valid IP addresses.
func ToCamelCase ¶
ToCamelCase converts a camelCase-ish string into a typical JSON camelCase string. Example conversion: MyJSONVariable -> myJsonVariable
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 // IsForPrefix returns whether or not the address is associated with the // passed bitcoin network. IsForPrefix(prefix Bech32Prefix) bool }
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, defaultPrefix Bech32Prefix) (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.
The bitcoin network address is associated with is extracted if possible. When the address does not encode the network, such as in the case of a raw public key, the address will be associated with the passed defaultNet.
type AddressPubKey ¶
type AddressPubKey struct {
// contains filtered or unexported fields
}
AddressPubKey is an Address for a pay-to-pubkey transaction.
func NewAddressPubKey ¶
func NewAddressPubKey(serializedPubKey []byte, prefix Bech32Prefix) (*AddressPubKey, error)
NewAddressPubKey returns a new AddressPubKey which represents a pay-to-pubkey address. The serializedPubKey parameter must be a valid pubkey and can be uncompressed, compressed, or hybrid.
func (*AddressPubKey) AddressPubKeyHash ¶
func (a *AddressPubKey) 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 Bitcoin addresses are pay-to-pubkey-hash constructed from the uncompressed public key.
func (*AddressPubKey) EncodeAddress ¶
func (a *AddressPubKey) 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 Bitcoin addresses are pay-to-pubkey-hash constructed from the uncompressed public key.
Part of the Address interface.
func (*AddressPubKey) Format ¶
func (a *AddressPubKey) Format() PubKeyFormat
Format returns the format (uncompressed, compressed, etc) of the pay-to-pubkey address.
func (*AddressPubKey) IsForPrefix ¶
func (a *AddressPubKey) IsForPrefix(prefix Bech32Prefix) bool
IsForPrefix returns whether or not the pay-to-pubkey address is associated with the passed bitcoin network.
func (*AddressPubKey) PubKey ¶
func (a *AddressPubKey) PubKey() *btcec.PublicKey
PubKey returns the underlying public key for the address.
func (*AddressPubKey) ScriptAddress ¶
func (a *AddressPubKey) 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 (*AddressPubKey) SetFormat ¶
func (a *AddressPubKey) SetFormat(pkFormat PubKeyFormat)
SetFormat sets the format (uncompressed, compressed, etc) of the pay-to-pubkey address.
func (*AddressPubKey) String ¶
func (a *AddressPubKey) 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, prefix Bech32Prefix) (*AddressPubKeyHash, error)
NewAddressPubKeyHash returns a new AddressPubKeyHash. pkHash mustbe 20 bytes.
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 appropiate than a slice (for example, when used as map keys).
func (*AddressPubKeyHash) IsForPrefix ¶
func (a *AddressPubKeyHash) IsForPrefix(prefix Bech32Prefix) bool
IsForPrefix returns whether or not the pay-to-pubkey-hash address is associated with the passed bitcoin network.
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, prefix Bech32Prefix) (*AddressScriptHash, error)
NewAddressScriptHash returns a new AddressScriptHash.
func NewAddressScriptHashFromHash ¶
func NewAddressScriptHashFromHash(scriptHash []byte, prefix Bech32Prefix) (*AddressScriptHash, error)
NewAddressScriptHashFromHash returns a new AddressScriptHash. scriptHash must be 20 bytes.
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 appropiate than a slice (for example, when used as map keys).
func (*AddressScriptHash) IsForPrefix ¶
func (a *AddressScriptHash) IsForPrefix(prefix Bech32Prefix) bool
IsForPrefix returns whether or not the pay-to-script-hash address is associated with the passed bitcoin network.
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 Amount ¶
type Amount uint64
Amount represents the base bitcoin monetary unit (colloquially referred to as a `Satoshi'). A single Amount is equal to 1e-8 of a bitcoin.
Example ¶
package main import ( "fmt" "github.com/daglabs/btcd/util" ) func main() { a := util.Amount(0) fmt.Println("Zero Satoshi:", a) a = util.Amount(1e8) fmt.Println("100,000,000 Satoshis:", a) a = util.Amount(1e5) fmt.Println("100,000 Satoshis:", a) }
Output: Zero Satoshi: 0 BTC 100,000,000 Satoshis: 1 BTC 100,000 Satoshis: 0.001 BTC
Example (UnitConversions) ¶
package main import ( "fmt" "github.com/daglabs/btcd/util" ) func main() { amount := util.Amount(44433322211100) fmt.Println("Satoshi to kBTC:", amount.Format(util.AmountKiloBTC)) fmt.Println("Satoshi to BTC:", amount) fmt.Println("Satoshi to MilliBTC:", amount.Format(util.AmountMilliBTC)) fmt.Println("Satoshi to MicroBTC:", amount.Format(util.AmountMicroBTC)) fmt.Println("Satoshi to Satoshi:", amount.Format(util.AmountSatoshi)) }
Output: Satoshi to kBTC: 444.333222111 kBTC Satoshi to BTC: 444333.222111 BTC Satoshi to MilliBTC: 444333222.111 mBTC Satoshi to MicroBTC: 444333222111 μBTC Satoshi to Satoshi: 44433322211100 Satoshi
func NewAmount ¶
NewAmount creates an Amount from a floating point value representing some value in bitcoin. NewAmount errors if f is NaN or +-Infinity, but does not check that the amount is within the total amount of bitcoin producible as f may not refer to an amount at a single moment in time.
NewAmount is for specifically for converting BTC to Satoshi. For creating a new Amount with an int64 value which denotes a quantity of Satoshi, do a simple type conversion from type int64 to Amount. See GoDoc for example: http://godoc.org/github.com/daglabs/btcutil#example-Amount
Example ¶
package main import ( "fmt" "math" "github.com/daglabs/btcd/util" ) func main() { amountOne, err := util.NewAmount(1) if err != nil { fmt.Println(err) return } fmt.Println(amountOne) //Output 1 amountFraction, err := util.NewAmount(0.01234567) if err != nil { fmt.Println(err) return } fmt.Println(amountFraction) //Output 2 amountZero, err := util.NewAmount(0) if err != nil { fmt.Println(err) return } fmt.Println(amountZero) //Output 3 amountNaN, err := util.NewAmount(math.NaN()) if err != nil { fmt.Println(err) return } fmt.Println(amountNaN) //Output 4 }
Output: 1 BTC 0.01234567 BTC 0 BTC invalid bitcoin amount
func (Amount) Format ¶
func (a Amount) Format(u AmountUnit) string
Format formats a monetary amount counted in bitcoin 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 "Satoshi" for the base unit.
func (Amount) MulF64 ¶
MulF64 multiplies an Amount by a floating point value. While this is not an operation that must typically be done by a full node or wallet, it is useful for services that build on top of bitcoin (for example, calculating a fee by multiplying by a percentage).
func (Amount) ToUnit ¶
func (a Amount) ToUnit(u AmountUnit) float64
ToUnit converts a monetary amount counted in bitcoin base units to a floating point value representing an amount of bitcoin.
type AmountUnit ¶
type AmountUnit int
AmountUnit describes a method of converting an Amount to something other than the base unit of a bitcoin. The value of the AmountUnit is the exponent component of the decadic multiple to convert from an amount in bitcoin to an amount counted in units.
const ( AmountMegaBTC AmountUnit = 6 AmountKiloBTC AmountUnit = 3 AmountBTC AmountUnit = 0 AmountMilliBTC AmountUnit = -3 AmountMicroBTC AmountUnit = -6 AmountSatoshi AmountUnit = -8 )
These constants define various units used when describing a bitcoin 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 "Satoshi" for the base unit. For all unrecognized units, "1eN BTC" is returned, where N is the AmountUnit.
type Bech32Prefix ¶
type Bech32Prefix int
Bech32Prefix is the human-readable prefix for a Bech32 address.
const ( // Unknown/Erroneous prefix Bech32PrefixUnknown Bech32Prefix = iota // Prefix for the main network. Bech32PrefixDAGCoin // Prefix for the regression test network. Bech32PrefixDAGReg // Prefix for the test network. Bech32PrefixDAGTest // Prefix for the simulation network. Bech32PrefixDAGSim )
Constants that define Bech32 address prefixes. Every network is assigned a unique prefix.
func ParsePrefix ¶
func ParsePrefix(prefixString string) (Bech32Prefix, error)
ParsePrefix attempts to parse a Bech32 address prefix.
func (Bech32Prefix) String ¶
func (prefix Bech32Prefix) String() string
Converts from Bech32 address prefixes to their string values
type Block ¶
type Block struct {
// contains filtered or unexported fields
}
Block defines a bitcoin block that provides easier and more efficient manipulation of raw blocks. It also memoizes hashes for the block and its transactions on their first access so subsequent accesses don't have to repeat the relatively expensive hashing operations.
func NewBlock ¶
NewBlock returns a new instance of a bitcoin block given an underlying wire.MsgBlock. See Block.
func NewBlockFromBlockAndBytes ¶
NewBlockFromBlockAndBytes returns a new instance of a bitcoin block given an underlying wire.MsgBlock and the serialized bytes for it. See Block.
func NewBlockFromBytes ¶
NewBlockFromBytes returns a new instance of a bitcoin block given the serialized bytes. See Block.
func NewBlockFromReader ¶
NewBlockFromReader returns a new instance of a bitcoin block given a Reader to deserialize the block. See Block.
func (*Block) Bytes ¶
Bytes returns the serialized bytes for the Block. This is equivalent to calling Serialize on the underlying wire.MsgBlock, however it caches the result so subsequent calls are more efficient.
func (*Block) CoinbaseTransaction ¶
CoinbaseTransaction returns this block's coinbase transaction
func (*Block) FeeTransaction ¶
FeeTransaction returns this block's fee transaction If this block is a genesis block, it has no fee transaction, and therefore nil is returned.
func (*Block) Hash ¶
Hash returns the block identifier hash for the Block. This is equivalent to calling BlockHash on the underlying wire.MsgBlock, however it caches the result so subsequent calls are more efficient.
func (*Block) Height ¶
Height returns the saved height of the block in the block chain. This value will be BlockHeightUnknown if it hasn't already explicitly been set.
func (*Block) Transactions ¶
Transactions returns a slice of wrapped transactions (util.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 (util.Tx) of them.
func (*Block) Tx ¶
Tx returns a wrapped transaction (util.Tx) for the transaction at the specified index in the Block. The supplied index is 0 based. That is to say, the first transaction in the block is txNum 0. This is nearly equivalent to accessing the raw transaction (wire.MsgTx) from the underlying wire.MsgBlock, however the wrapped transaction has some helpful properties such as caching the hash so subsequent calls are more efficient.
func (*Block) TxHash ¶
TxHash returns the hash for the requested transaction number in the Block. The supplied index is 0 based. That is to say, the first transaction in the block is txNum 0. This is equivalent to calling TxHash on the underlying wire.MsgTx, however it caches the result so subsequent calls are more efficient.
type 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 // PKFHybrid indicates the pay-to-pubkey address format is a hybrid // public key. PKFHybrid )
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx defines a bitcoin 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 ¶
NewTx returns a new instance of a bitcoin transaction given an underlying wire.MsgTx. See Tx.
func NewTxFromBytes ¶
NewTxFromBytes returns a new instance of a bitcoin transaction given the serialized bytes. See Tx.
func NewTxFromReader ¶
NewTxFromReader returns a new instance of a bitcoin transaction given a Reader to deserialize the transaction. See Tx.
func (*Tx) Hash ¶
Hash returns the hash of the transaction. This is equivalent to calling TxHash on the underlying wire.MsgTx, however it caches the result so subsequent calls are more efficient.
func (*Tx) ID ¶
ID returns the id of the transaction. This is equivalent to calling TxID on the underlying wire.MsgTx, however it caches the result so subsequent calls are more efficient.
func (*Tx) Index ¶
Index returns the saved index of the transaction within a block. This value will be TxIndexUnknown if it hasn't already explicitly been set.
type WIF ¶
type WIF struct { // PrivKey is the private key being imported or exported. PrivKey *btcec.PrivateKey // CompressPubKey specifies whether the address controlled by the // imported or exported private key was created by hashing a // compressed (33-byte) serialized public key, rather than an // uncompressed (65-byte) one. CompressPubKey bool // contains filtered or unexported fields }
WIF contains the individual components described by the Wallet Import Format (WIF). A WIF string is typically used to represent a private key and its associated address in a way that may be easily copied and imported into or exported from wallet software. WIF strings may be decoded into this structure by calling DecodeWIF or created with a user-provided private key by calling NewWIF.
func DecodeWIF ¶
DecodeWIF creates a new WIF structure by decoding the string encoding of the import format.
The WIF string must be a base58-encoded string of the following byte sequence:
- 1 byte to identify the network, must be 0x80 for mainnet or 0xef for either testnet3 or the regression test network
- 32 bytes of a binary-encoded, big-endian, zero-padded private key
- Optional 1 byte (equal to 0x01) if the address being imported or exported was created by taking the RIPEMD160 after SHA256 hash of a serialized compressed (33-byte) public 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 or the expected compressed pubkey magic number does not equal the expected value of 0x01. ErrChecksumMismatch is returned if the expected WIF checksum does not match the calculated checksum.
func NewWIF ¶
NewWIF creates a new WIF structure to export an address and its private key as a string encoded in the Wallet Import Format. The 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) IsForNet ¶
IsForNet returns whether or not the decoded WIF structure is associated with the passed bitcoin network.
func (*WIF) SerializePubKey ¶
SerializePubKey serializes the associated public key of the imported or exported private key in either a compressed or uncompressed format. The serialization format chosen depends on the value of w.CompressPubKey.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package base58 provides an API for working with modified base58 and Base58Check encodings.
|
Package base58 provides an API for working with modified base58 and Base58Check encodings. |
Package bech32 provides a Go implementation of the bech32 format.
|
Package bech32 provides a Go implementation of the bech32 format. |
Package gcs provides an API for building and using a Golomb-coded set filter.
|
Package gcs provides an API for building and using a Golomb-coded set filter. |
Package hdkeychain provides an API for bitcoin hierarchical deterministic extended keys (BIP0032).
|
Package hdkeychain provides an API for bitcoin hierarchical deterministic extended keys (BIP0032). |
Package txsort provides the transaction sorting according to BIP 69.
|
Package txsort provides the transaction sorting according to BIP 69. |