bchutil

package module
v0.0.0-...-9ef0dd4 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: ISC Imports: 32 Imported by: 315

README

bchutil

Build Status ISC License GoDoc

Package bchutil provides bitcoin cash-specific convenience functions and types. A comprehensive suite of tests is provided to ensure proper functionality. See test_coverage.txt for the gocov coverage report. Alternatively, if you are running a POSIX OS, you can run the cov_report.sh script for a real-time report.

This package was developed for bchd, an alternative full-node implementation of bitcoin cash. Although it was primarily written for bchd, 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/gcash/bchutil

License

Package bchutil is licensed under the copyfree ISC License.

Documentation

Overview

Package bchutil provides bitcoin cash-specific convenience functions and types.

Block Overview

A Block defines a bitcoin cash 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 cash 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 Cashaddress. While the most common type is a pay-to-pubkey-hash, Bitcoin Cash 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 := bchutil.DecodeAddress(addrString, defaultNet)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(addr.EncodeAddress())

Index

Examples

Constants

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

View Source
const Charset string = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"

Charset is the base32 character set for the cashaddr.

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
	// begining 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")

	// ErrInvalidFormat describes an error where decoding failed due to invalid version
	ErrInvalidFormat = errors.New("invalid format: version and/or checksum bytes missing")

	// ErrUnknownFormat describes an error that occurs when an address cannot be
	// decoded because it has an unknown format.
	ErrUnknownFormat = errors.New("decoded address is of unknown format")
)
View Source
var CharsetRev = [128]int8{}/* 128 elements not displayed */

CharsetRev is the cashaddr character set for decoding.

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 DecodeCashAddress

func DecodeCashAddress(str string) (string, []byte, error)

DecodeCashAddress decodes a cashaddr string and returns the prefix and data element.

func Hash160

func Hash160(buf []byte) []byte

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

func Hash256

func Hash256(buf []byte) []byte

Hash256 calculates the hash sha256(sha256(b)).

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 256-bit ECDSA private key. The machine's local interface addresses and all variants of IPv4 and IPv6 localhost are included as valid IP addresses.

256-bit ECDSA is chosen so a single cert can support both RPC and gRPC connections when auto generating certificates in bchd.

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

	// IsForNet returns whether or not the address is associated with the
	// passed bitcoin network.
	IsForNet(*chaincfg.Params) 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 ConvertCashToSlpAddress

func ConvertCashToSlpAddress(addr Address, params *chaincfg.Params) (Address, error)

TODO add p2sh32? ConvertCashToSlpAddress converts a cash formatted address to slp formatted address

func ConvertSlpToCashAddress

func ConvertSlpToCashAddress(addr Address, params *chaincfg.Params) (Address, error)

TODO add p2sh32? ConvertSlpToCashAddress converts an slp formatted address to cash formatted address

func DecodeAddress

func DecodeAddress(addr string, defaultNet *chaincfg.Params) (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 the 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, net *chaincfg.Params) (*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) IsForNet

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

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

func (*AddressPubKey) PubKey

func (a *AddressPubKey) PubKey() *bchec.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, net *chaincfg.Params) (*AddressPubKeyHash, error)

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

func NewSlpAddressPubKeyHash

func NewSlpAddressPubKeyHash(pkHash []byte, net *chaincfg.Params) (*AddressPubKeyHash, error)

NewSlpAddressPubKeyHash returns a new Slp formatted AddressPubKeyHash.

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) 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 bitcoin cash 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, 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 NewSlpAddressScriptHashFromHash

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

NewSlpAddressScriptHashFromHash returns a new Slp formatted AddressScriptHash.

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) 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 bitcoin cash 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 AddressScriptHash32

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

AddressScriptHash32 is an Address for a pay-to-script-hash32 (P2SH32) transaction.

func NewAddressScriptHash32

func NewAddressScriptHash32(serializedScript []byte, net *chaincfg.Params) (*AddressScriptHash32, error)

NewAddressScriptHash32 returns a new AddressScriptHash32.

func NewAddressScriptHash32FromHash

func NewAddressScriptHash32FromHash(scriptHash []byte, net *chaincfg.Params) (*AddressScriptHash32, error)

NewAddressScriptHash32FromHash returns a new AddressScriptHash32. scriptHash must be 32 bytes.

func NewSlpAddressScriptHash32FromHash

func NewSlpAddressScriptHash32FromHash(scriptHash []byte, net *chaincfg.Params) (*AddressScriptHash32, error)

NewSlpAddressScriptHash32FromHash returns a new Slp formatted AddressScriptHash32.

func (*AddressScriptHash32) EncodeAddress

func (a *AddressScriptHash32) EncodeAddress() string

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

func (*AddressScriptHash32) Hash256

func (a *AddressScriptHash32) Hash256() *[sha256.Size]byte

Hash256 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 (*AddressScriptHash32) IsForNet

func (a *AddressScriptHash32) IsForNet(net *chaincfg.Params)