bt

package module
v2.0.0-beta Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2021 License: ISC Imports: 11 Imported by: 69

README

go-bt

The go-to Bitcoin Transaction (BT) GoLang library

Release Build Status Report codecov Go Sponsor Donate


Table of Contents


Installation

go-bt requires a supported release of Go.

go get -u github.com/libsv/go-bt

Documentation

View the generated documentation

GoDoc

For more information around the technical aspects of Bitcoin, please see the updated Bitcoin Wiki


Features
  • Full Featured Bitcoin Transactions

  • Auto-Fee Calculations for Change Address

  • Bitcoin Transaction Script Functionality

    • P2PKH (base58 addresses)
    • Data (OP_RETURN)
    • BIP276
  • Transaction Signing Extendability

Coming Soon! (18 monthsTM)
  • Complete SigHash Flag Capability
  • MultiSig functionality
Library Deployment

goreleaser for easy binary or library deployment to Github and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

make help

List of all current commands:

all                  Runs multiple commands
clean                Remove previous builds and any test cache data
clean-mods           Remove all the Go mod cache
coverage             Shows the test coverage
godocs               Sync the latest tag with GoDocs
help                 Show this help message
install              Install the application
install-go           Install the application (Using Native Go)
lint                 Run the golangci-lint application (install if not found)
release              Full production release (creates release in Github)
release              Runs common.release then runs godocs
release-snap         Test the full release (build binaries)
release-test         Full production test release (everything except deploy)
replace-version      Replaces the version in HTML/JS (pre-deploy)
tag                  Generate a new tag and push (tag version=0.0.0)
tag-remove           Remove a tag if found (tag-remove version=0.0.0)
tag-update           Update an existing tag to current commit (tag-update version=0.0.0)
test                 Runs vet, lint and ALL tests
test-ci              Runs all tests via CI (exports coverage)
test-ci-no-race      Runs all tests via CI (no race) (exports coverage)
test-ci-short        Runs unit tests via CI (exports coverage)
test-short           Runs vet, lint and tests (excludes integration tests)
uninstall            Uninstall the application (and remove files)
update-linter        Update the golangci-lint package (macOS only)
vet                  Run the Go vet application

Examples & Tests

All unit tests and examples run via Github Actions and uses Go version 1.15.x. View the configuration file.

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.


Usage

View the examples


Maintainers

JH JW MrZ
JH JW MrZ

Contributing

View the contributing guidelines and please follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏 or by making a bitcoin donation to ensure this journey continues indefinitely! 🚀


License

License

Documentation

Overview

Package bt provides functions needed to create and manipulate Bitcoin transactions.

Index

Constants

View Source
const DefaultSequenceNumber uint32 = 0xFFFFFFFF

DefaultSequenceNumber is the default starting sequence number

Variables

View Source
var (
	ErrInvalidTxID = errors.New("invalid TxID")
)

Sentinel errors for transactions.

Functions

func DecodeVarInt

func DecodeVarInt(b []byte) (result uint64, size int)

DecodeVarInt takes a byte array in VarInt format and returns the decoded unsigned integer value of the length and it's size in bytes. See http://learnmeabitcoin.com/glossary/varint

func IsValidTxID

func IsValidTxID(txid []byte) bool

IsValidTxID will check that the txid bytes are valid.

A txid should be of 32 bytes length.

func LittleEndianBytes

func LittleEndianBytes(v uint32, l uint32) []byte

LittleEndianBytes returns a byte array in little endian from an unsigned integer of 32 bytes.

func ReverseBytes

func ReverseBytes(a []byte) []byte

ReverseBytes reverses the bytes (little endian/big endian). This is used when computing merkle trees in Bitcoin, for example.

func VarInt

func VarInt(i uint64) []byte

VarInt takes an unsigned integer and returns a byte array in VarInt format. See http://learnmeabitcoin.com/glossary/varint

func VarIntUpperLimitInc

func VarIntUpperLimitInc(length uint64) int

VarIntUpperLimitInc returns true if a number is at the upper limit of a VarInt and will result in a VarInt length change if incremented. The value returned will indicate how many bytes will be increase if the length in incremented. -1 will be returned when the upper limit of VarInt is reached.

Types

type AutoSigner

type AutoSigner interface {
	Signer
	PublicKey(ctx context.Context) (publicKey []byte, err error)
}

AutoSigner interface to allow custom implementations of different signing mechanisms. Implement the Sign function as shown in InternalSigner, for example. Sign generates and returns an ECDSA signature for the provided hash digest using the private key as well as the public key corresponding to the private key used. The produced signature is deterministic (same message and same key yield the same signature) and canonical in accordance with RFC6979 and BIP0062.

To automatically sign, the PublicKey() method must also be implemented in order to use the public key to check which Inputs can be signed for before signing.

type Fee

type Fee struct {
	FeeType   FeeType `json:"feeType"` // standard || data
	MiningFee FeeUnit `json:"miningFee"`
	RelayFee  FeeUnit `json:"relayFee"` // Fee for retaining Tx in secondary mempool
}

Fee displays the MiningFee as well as the RelayFee for a specific FeeType, for example 'standard' or 'data' see https://github.com/bitcoin-sv-specs/brfc-misc/tree/master/feespec

func DefaultDataFee

func DefaultDataFee() *Fee

DefaultDataFee returns the default data fees offered by most miners.

func DefaultFees

func DefaultFees() (f []*Fee)

DefaultFees returns an array of the default standard and data fees offered by most miners.

func DefaultStandardFee

func DefaultStandardFee() *Fee

DefaultStandardFee returns the default standard fees offered by most miners.

func ExtractDataFee

func ExtractDataFee(fees []*Fee) (*Fee, error)

ExtractDataFee returns the data fee in the fees array supplied.

func ExtractStandardFee

func ExtractStandardFee(fees []*Fee) (*Fee, error)

ExtractStandardFee returns the standard fee in the fees array supplied.

type FeeType

type FeeType string

FeeType is used to specify which type of fee is used depending on the type of tx data (eg: standard bytes or data bytes).

const (
	// FeeTypeStandard is the fee type for standard tx parts
	FeeTypeStandard FeeType = "standard"

	// FeeTypeData is the fee type for data tx parts
	FeeTypeData FeeType = "data"
)

type FeeUnit

type FeeUnit struct {
	Satoshis int `json:"satoshis"` // Fee in satoshis of the amount of Bytes
	Bytes    int `json:"bytes"`    // Number of bytes that the Fee covers
}

FeeUnit displays the amount of Satoshis needed for a specific amount of Bytes in a transaction see https://github.com/bitcoin-sv-specs/brfc-misc/tree/master/feespec

type Input

type Input struct {
	PreviousTxSatoshis uint64
	PreviousTxScript   *bscript.Script
	UnlockingScript    *bscript.Script
	PreviousTxOutIndex uint32
	SequenceNumber     uint32
	// contains filtered or unexported fields
}

Input is a representation of a transaction input

DO NOT CHANGE ORDER - Optimised for memory via maligned

func NewInputFromBytes

func NewInputFromBytes(bytes []byte) (*Input, int, error)

NewInputFromBytes returns a transaction input from the bytes provided.

func (*Input) Bytes

func (i *Input) Bytes(clear bool) []byte

Bytes encodes the Input into a hex byte array.

func (*Input) MarshalJSON

func (i *Input) MarshalJSON() ([]byte, error)

MarshalJSON will convert an input to json, expanding upon the input struct to add additional fields.

func (*Input) PreviousTxID

func (i *Input) PreviousTxID() []byte

PreviousTxID will return the PreviousTxID if set.

func (*Input) PreviousTxIDAdd

func (i *Input) PreviousTxIDAdd(txID []byte) error

PreviousTxIDAdd will add the supplied txID bytes to the Input, if it isn't a valid transaction id an ErrInvalidTxID error will be returned.

func (*Input) PreviousTxIDAddStr

func (i *Input) PreviousTxIDAddStr(txID string) error

PreviousTxIDAddStr will validate and add the supplied txID string to the Input, if it isn't a valid transaction id an ErrInvalidTxID error will be returned.

func (*Input) PreviousTxIDStr

func (i *Input) PreviousTxIDStr() string

PreviousTxIDStr returns the Previous TxID as a hex string.

func (*Input) String

func (i *Input) String() string

String implements the Stringer interface and returns a string representation of a transaction input.

func (*Input) UnmarshalJSON

func (i *Input) UnmarshalJSON(b []byte) error

UnmarshalJSON will convert a JSON input to an input.

type LocalSigner

type LocalSigner struct {
	PrivateKey *bec.PrivateKey
}

LocalSigner implements the Signer interface. It is used to sign Tx Inputs locally using a bkec PrivateKey.

func (*LocalSigner) PublicKey

func (is *LocalSigner) PublicKey(ctx context.Context) (publicKey []byte, err error)

PublicKey returns the public key which will be used to sign.

func (*LocalSigner) Sign

func (is *LocalSigner) Sign(ctx context.Context, unsignedTx *Tx, index uint32,
	shf sighash.Flag) (publicKey []byte, signature []byte, err error)

Sign a transaction at a given input index using the PrivateKey passed in through the InternalSigner struct.

func (*LocalSigner) SignHash

func (is *LocalSigner) SignHash(ctx context.Context, hash []byte) (publicKey, signature []byte, err error)

SignHash a transaction at a given a hash digest using the PrivateKey passed in through the InternalSigner struct.

type Output

type Output struct {
	Satoshis      uint64
	LockingScript *bscript.Script
	// contains filtered or unexported fields
}

Output is a representation of a transaction output

func NewOutputFromBytes

func NewOutputFromBytes(bytes []byte) (*Output, int, error)

NewOutputFromBytes returns a transaction Output from the bytes provided

func (*Output) Bytes

func (o *Output) Bytes() []byte

Bytes encodes the Output into a byte array.

func (*Output) BytesForSigHash

func (o *Output) BytesForSigHash() []byte

BytesForSigHash returns the proper serialisation of an output to be hashed and signed (sighash).

func (*Output) LockingScriptHexString

func (o *Output) LockingScriptHexString() string

LockingScriptHexString returns the locking script of an output encoded as a hex string.

func (*Output) MarshalJSON

func (o *Output) MarshalJSON() ([]byte, error)

MarshalJSON will serialise an output to json.

func (*Output) String

func (o *Output) String() string

func (*Output) UnmarshalJSON

func (o *Output) UnmarshalJSON(b []byte) error

UnmarshalJSON will convert a json serialised output to a bt Output.

type Signer

type Signer interface {
	Sign(ctx context.Context, unsignedTx *Tx, index uint32, shf sighash.Flag) (publicKey, signature []byte, err error)
	SignHash(ctx context.Context, hash []byte) (publicKey, signature []byte, err error)
}

Signer interface to allow custom implementations of different signing mechanisms. Implement the Sign function as shown in InternalSigner, for example. Sign generates and returns an ECDSA signature for the provided hash digest using the private key as well as the public key corresponding to the private key used. The produced signature is deterministic (same message and same key yield the same signature) and canonical in accordance with RFC6979 and BIP0062.

type Tx

type Tx struct {
	Inputs   []*Input
	Outputs  []*Output
	Version  uint32
	LockTime uint32
}

Tx wraps a bitcoin transaction

DO NOT CHANGE ORDER - Optimised memory via malign

func NewTx

func NewTx() *Tx

NewTx creates a new transaction object with default values.

func NewTxFromBytes

func NewTxFromBytes(b []byte) (*Tx, error)

NewTxFromBytes takes an array of bytes, constructs a Tx and returns it. This function assumes that the byte slice contains exactly 1 transaction.

func NewTxFromStream

func NewTxFromStream(b []byte) (*Tx, int, error)

NewTxFromStream takes an array of bytes and constructs a Tx from it, returning the Tx and the bytes used. Despite the name, this is not actually reading a stream in the true sense: it is a byte slice that contains many transactions one after another.

func NewTxFromString

func NewTxFromString(str string) (*Tx, error)

NewTxFromString takes a toBytesHelper string representation of a bitcoin transaction and returns a Tx object.

func (*Tx) AddHashPuzzleOutput

func (tx *Tx) AddHashPuzzleOutput(secret, publicKeyHash string, satoshis uint64) error

AddHashPuzzleOutput makes an output to a hash puzzle + PKH with a value.

func (*Tx) AddOpReturnOutput

func (tx *Tx) AddOpReturnOutput(data []byte) error

AddOpReturnOutput creates a new Output with OP_FALSE OP_RETURN and then the data passed in encoded as hex.

func (*Tx) AddOpReturnPartsOutput

func (tx *Tx) AddOpReturnPartsOutput(data [][]byte) error

AddOpReturnPartsOutput creates a new Output with OP_FALSE OP_RETURN and then uses OP_PUSHDATA format to encode the multiple byte arrays passed in.

func (*Tx) AddOutput

func (tx *Tx) AddOutput(output *Output)

AddOutput adds a new output to the transaction.

func (*Tx) AddP2PKHInputsFromTx

func (tx *Tx) AddP2PKHInputsFromTx(pvsTx *Tx, matchPK []byte) error

AddP2PKHInputsFromTx will add all Outputs of given previous transaction that match a specific public key to your transaction.

func (*Tx) AddP2PKHOutputFromAddress

func (tx *Tx) AddP2PKHOutputFromAddress(addr string, satoshis uint64) error

AddP2PKHOutputFromAddress makes an output to a PKH with a value.

func (*Tx) AddP2PKHOutputFromPubKeyBytes

func (tx *Tx) AddP2PKHOutputFromPubKeyBytes(publicKeyBytes []byte, satoshis uint64) error

AddP2PKHOutputFromPubKeyBytes makes an output to a PKH with a value.

func (*Tx) AddP2PKHOutputFromPubKeyHashStr

func (tx *Tx) AddP2PKHOutputFromPubKeyHashStr(publicKeyHash string, satoshis uint64) error

AddP2PKHOutputFromPubKeyHashStr makes an output to a PKH with a value.

func (*Tx) AddP2PKHOutputFromPubKeyStr

func (tx *Tx) AddP2PKHOutputFromPubKeyStr(publicKey string, satoshis uint64) error

AddP2PKHOutputFromPubKeyStr makes an output to a PKH with a value.

func (*Tx) AddP2PKHOutputFromScript

func (tx *Tx) AddP2PKHOutputFromScript(script *bscript.Script, satoshis uint64) error

AddP2PKHOutputFromScript makes an output to a P2PKH script paid to the provided locking script with a value.

func (*Tx) ApplyP2PKHUnlockingScript

func (tx *Tx) ApplyP2PKHUnlockingScript(index uint32, pubKey []byte, sig []byte, shf sighash.Flag) error

ApplyP2PKHUnlockingScript applies a script to the transaction at a specific index in unlocking script field.

func (*Tx) ApplyUnlockingScript

func (tx *Tx) ApplyUnlockingScript(index uint32, s *bscript.Script) error

ApplyUnlockingScript applies a script to the transaction at a specific index in unlocking script field.

func (*Tx) Bytes

func (tx *Tx) Bytes() []byte

Bytes encodes the transaction into a byte array. See https://chainquery.com/bitcoin-cli/decoderawtransaction

func (*Tx) BytesWithClearedInputs

func (tx *Tx) BytesWithClearedInputs(index int, lockingScript []byte) []byte

BytesWithClearedInputs encodes the transaction into a byte array but clears its Inputs first. This is used when signing transactions.

func (*Tx) CalcInputPreimage

func (tx *Tx) CalcInputPreimage(inputNumber uint32, sigHashFlag sighash.Flag) ([]byte, error)

CalcInputPreimage serialises the transaction based on the input index and the SIGHASH flag and returns the preimage before double hashing (SHA256d).

see https://github.com/bitcoin-sv/bitcoin-sv/blob/master/doc/abc/replay-protected-sighash.md#digest-algorithm

func (*Tx) CalcInputSignatureHash

func (tx *Tx) CalcInputSignatureHash(inputNumber uint32, sigHashFlag sighash.Flag) ([]byte, error)

CalcInputSignatureHash serialised the transaction and returns the hash digest to be signed. BitCoin (SV) uses a different signature hashing algorithm after the UAHF fork for replay protection.

see https://github.com/bitcoin-sv/bitcoin-sv/blob/master/doc/abc/replay-protected-sighash.md#digest-algorithm

func (*Tx) CalculateFee

func (tx *Tx) CalculateFee(f []*Fee) (uint64, error)

CalculateFee will return the amount of fees the current transaction will require.

func (*Tx) Change

func (tx *Tx) Change(s *bscript.Script, f []*Fee) error

Change calculates the amount of fees needed to cover the transaction

and adds the left over change in a new output using the script provided.

func (*Tx) ChangeToAddress

func (tx *Tx) ChangeToAddress(addr string, f []*Fee) error

ChangeToAddress calculates the amount of fees needed to cover the transaction and adds the left over change in a new P2PKH output using the address provided.

func (*Tx) ChangeToExistingOutput

func (tx *Tx) ChangeToExistingOutput(index uint, f []*Fee) error

ChangeToExistingOutput will calculate fees and add them to an output at the index specified (0 based). If an invalid index is supplied and error is returned.

func (*Tx) From

func (tx *Tx) From(prevTxID string, vout uint32, prevTxLockingScript string, satoshis uint64) error

From adds a new input to the transaction from the specified UTXO fields, using the default finalised sequence number (0xFFFFFFFF). If you want a different nSeq, change it manually afterwards.

func (*Tx) HasDataOutputs

func (tx *Tx) HasDataOutputs() bool

HasDataOutputs returns true if the transaction has at least one data (OP_RETURN) output in it.

func (*Tx) InputCount

func (tx *Tx) InputCount() int

InputCount returns the number of transaction Inputs.

func (*Tx) InputIdx

func (tx *Tx) InputIdx(i int) *Input

InputIdx will return the input at the specified index.

This will consume an overflow error and simply return nil if the input isn't found at the index.

func (*Tx) IsCoinbase

func (tx *Tx) IsCoinbase() bool

IsCoinbase determines if this transaction is a coinbase by checking if the tx input is a standard coinbase input.

func (*Tx) MarshalJSON

func (tx *Tx) MarshalJSON() ([]byte, error)

MarshalJSON will serialise a transaction to json.

func (*Tx) OutputCount

func (tx *Tx) OutputCount() int

OutputCount returns the number of transaction Inputs.

func (*Tx) OutputIdx

func (tx *Tx) OutputIdx(i int) *Output

OutputIdx will return the output at the specified index.

This will consume an overflow error and simply return nil if the output isn't found at the index.

func (*Tx) PayTo

func (tx *Tx) PayTo(script *bscript.Script, satoshis uint64) error

PayTo creates a new P2PKH output from a BitCoin address (base58) and the satoshis amount and adds that to the transaction.

func (*Tx) PayToAddress

func (tx *Tx) PayToAddress(addr string, satoshis uint64) error

PayToAddress creates a new P2PKH output from a BitCoin address (base58) and the satoshis amount and adds that to the transaction.

func (*Tx) Sign

func (tx *Tx) Sign(ctx context.Context, s Signer, index uint32, shf sighash.Flag) error

Sign is used to sign the transaction at a specific input index. It takes a Signed interface as a parameter so that different signing implementations can be used to sign the transaction - for example internal/local or external signing (hardware wallet).

func (*Tx) SignAuto

func (tx *Tx) SignAuto(ctx context.Context, s AutoSigner) (inputsSigned []int, err error)

SignAuto is used to automatically check which P2PKH Inputs are able to be signed (match the public key) and then sign them. It takes a Signed interface as a parameter so that different signing implementations can be used to sign the transaction - for example internal/local or external signing.

func (*Tx) SignHash

func (tx *Tx) SignHash(ctx context.Context, s Signer, index uint32, shf sighash.Flag) error

SignHash is used to sign the transaction at a specific input index. It takes a Signed interface as a parameter so that different signing implementations can be used to sign the transaction - for example internal/local or external signing (hardware wallet).

SignHash will only take the final signature hash to be signed so will need to trust that it is getting the right hash to sign as there no way to verify that it is signing the right hash.

func (*Tx) String

func (tx *Tx) String() string

String encodes the transaction into a hex string.

func (*Tx) TotalInputSatoshis

func (tx *Tx) TotalInputSatoshis() (total uint64)

TotalInputSatoshis returns the total Satoshis inputted to the transaction.

func (*Tx) TotalOutputSatoshis

func (tx *Tx) TotalOutputSatoshis() (total uint64)

TotalOutputSatoshis returns the total Satoshis outputted from the transaction.

func (*Tx) TxID

func (tx *Tx) TxID() string

TxID returns the transaction ID of the transaction (which is also the transaction hash).

func (*Tx) TxIDBytes

func (tx *Tx) TxIDBytes() []byte

TxIDBytes returns the transaction ID of the transaction as bytes (which is also the transaction hash).

func (*Tx) UnmarshalJSON

func (tx *Tx) UnmarshalJSON(b []byte) error

UnmarshalJSON will unmarshall a transaction that has been marshalled with this library.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL