Documentation
¶
Overview ¶
Package btcutil 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 := btcutil.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 InterfaceAddrs() ([]net.Addr, error)
- func NewTLSCertPair(organization string, validUntil time.Time, extraHosts []string) (cert, key []byte, err error)
- type Amount
- type AmountUnit
- type Block
- func (b *Block) Bytes() ([]byte, error)
- func (b *Block) BytesNoWitness() ([]byte, error)
- func (b *Block) Hash() *chainhash.Hash
- func (b *Block) Height() int32
- 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) (*chainhash.Hash, error)
- func (b *Block) TxLoc() ([]wire.TxLoc, error)
- type OutOfRangeError
- type Tx
- type WIF
Examples ¶
Constants ¶
const ( // SatoshiPerBitcent is the number of satoshi in one bitcoin cent. SatoshiPerBitcent = 1e6 // SatoshiPerBitcoin is the number of satoshi in one bitcoin (1 BTC). SatoshiPerBitcoin = 1e8 // MaxSatoshi is the maximum transaction amount allowed in satoshi. MaxSatoshi = 21e6 * SatoshiPerBitcoin )
const BlockHeightUnknown = int32(-1)
BlockHeightUnknown is the value returned for a block height that is unknown. This is typically because the block has not been inserted into the main chain yet.
const TxIndexUnknown = -1
TxIndexUnknown is the value returned for a transaction index that is unknown. This is typically because the transaction has not been inserted into a block yet.
Variables ¶
var ErrMalformedPrivateKey = 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 InterfaceAddrs ¶
InterfaceAddrs returns a list of the system's network interface addresses. It is wrapped here so that we can substitute it for other functions when building for systems that do not allow access to net.InterfaceAddrs().
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.
Types ¶
type Amount ¶
type Amount int64
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/ace-network-oss/ace/btcutil"
)
func main() {
a := btcutil.Amount(0)
fmt.Println("Zero Chip:", a)
a = btcutil.Amount(1e8)
fmt.Println("100,000,000 Satoshis:", a)
a = btcutil.Amount(1e5)
fmt.Println("100,000 Satoshis:", a)
}
Output: Zero Chip: 0 ACE 100,000,000 Satoshis: 1 ACE 100,000 Satoshis: 0.00100000 ACE
Example (UnitConversions) ¶
package main
import (
"fmt"
"github.com/ace-network-oss/ace/btcutil"
)
func main() {
amount := btcutil.Amount(44433322211100)
fmt.Println("Satoshi to kACE:", amount.Format(btcutil.AmountKiloBTC))
fmt.Println("Satoshi to ACE:", amount)
fmt.Println("Satoshi to MilliBTC:", amount.Format(btcutil.AmountMilliBTC))
fmt.Println("Satoshi to MicroBTC:", amount.Format(btcutil.AmountMicroBTC))
fmt.Println("Satoshi to Chip:", amount.Format(btcutil.AmountSatoshi))
}
Output: Satoshi to kACE: 444.333222111 kACE Satoshi to ACE: 444333.22211100 ACE Satoshi to MilliBTC: 444333222.111 mACE Satoshi to MicroBTC: 444333222111 μACE Satoshi to Chip: 44433322211100 Chip
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/ace-network-oss/ace/btcutil#example-Amount
Example ¶
package main
import (
"fmt"
"math"
"github.com/ace-network-oss/ace/btcutil"
)
func main() {
amountOne, err := btcutil.NewAmount(1)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(amountOne) //Output 1
amountFraction, err := btcutil.NewAmount(0.01234567)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(amountFraction) //Output 2
amountZero, err := btcutil.NewAmount(0)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(amountZero) //Output 3
amountNaN, err := btcutil.NewAmount(math.NaN())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(amountNaN) //Output 4
}
Output: 1 ACE 0.01234567 ACE 0 ACE invalid ACE 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 formatted 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 "Chip" for the base unit. For all unrecognized units, "1eN ACE" is returned, where N is the AmountUnit.
The AmountMegaBTC-style identifiers keep their inherited names so that this package stays source compatible with btcd's; only the rendered strings differ.
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) BytesNoWitness ¶
BytesNoWitness returns the serialized bytes for the block with transactions encoded without any witness data.
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 (btcutil.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 (btcutil.Tx) of them.
func (*Block) Tx ¶
Tx returns a wrapped transaction (btcutil.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 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) HasWitness ¶
HasWitness returns false if none of the inputs within the transaction contain witness data, true false otherwise. This equivalent to calling HasWitness on the underlying wire.MsgTx, however it caches the result so subsequent calls are more efficient.
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. If the Tx has the raw bytes of the tx cached, it will use that and skip serialization.
func (*Tx) Index ¶
Index returns the saved index of the transaction within a block. This value will be TxIndexUnknown if it hasn't already explicitly been set.
func (*Tx) WitnessHash ¶
WitnessHash returns the witness hash (wtxid) of the transaction. This is equivalent to calling WitnessHash on the underlying wire.MsgTx, however it caches the result so subsequent calls are more efficient. If the Tx has the raw bytes of the tx cached, it will use that and skip serialization.
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 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. |