bt

package module
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2022 License: ISC Imports: 10 Imported by: 16

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 (
	// FeeTypeStandard is the fee type for standard tx parts
	FeeTypeStandard = "standard"

	// FeeTypeData is the fee type for data tx parts
	FeeTypeData = "data"
)
View Source
const DefaultSequenceNumber uint32 = 0xFFFFFFFF

DefaultSequenceNumber is the default starting sequence number

View Source
const (
	// DustLimit is the current minimum output satoshis accepted by the network.
	DustLimit = 136
)

Variables

This section is empty.

Functions

func DecodeVarInt

func DecodeVarInt(b []byte) (uint64, 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 DecodeVarIntFromReader added in v1.0.1

func DecodeVarIntFromReader(r io.Reader) (uint64, int, error)

DecodeVarIntFromReader takes an io.Reader and returns the decoded unsigned integer value of the length. See http://learnmeabitcoin.com/glossary/varint

func GetLittleEndianBytes

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

GetLittleEndianBytes 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 Fee

type Fee struct {
	FeeType   string  `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 GetDataFee

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

GetDataFee returns the data fee in the fees array supplied.

func GetStandardFee

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

GetStandardFee returns the standard fee in the fees array supplied.

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 {
	PreviousTxIDBytes  []byte
	PreviousTxID       string
	PreviousTxSatoshis uint64
	PreviousTxScript   *bscript.Script
	UnlockingScript    *bscript.Script
	PreviousTxOutIndex uint32
	SequenceNumber     uint32
}

Input is a representation of a transaction input

DO NOT CHANGE ORDER - Optimized for memory via maligned

func NewInput

func NewInput() *Input

NewInput creates a new empty Input object with a finalized sequence number.

func NewInputFromBytes

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

NewInputFromBytes returns a transaction input from the bytes provided.

func NewInputFromReader added in v1.0.1

func NewInputFromReader(r io.Reader) (*Input, error)

NewInputFromReader returns a transaction input from the io.Reader provided.

func NewInputFromUTXO

func NewInputFromUTXO(prevTxID string, prevTxIndex uint32, prevTxSats uint64,
	prevTxScript string, nSeq uint32) (*Input, error)

NewInputFromUTXO returns a transaction input from the UTXO fields provided.

func (*Input) String

func (i *Input) String() string

func (*Input) ToBytes

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

ToBytes encodes the Input into a hex byte array.

type InternalSigner

type InternalSigner struct {
	PrivateKey  *bsvec.PrivateKey
	SigHashFlag sighash.Flag
}

InternalSigner implements the Signer interface. It is used to sign a Tx locally given a PrivateKey and SIGHASH type.

func (*InternalSigner) Sign

func (is *InternalSigner) Sign(index uint32, unsignedTx *Tx) (signedTx *Tx, err error)

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

func (*InternalSigner) SignAuto

func (is *InternalSigner) SignAuto(unsignedTx *Tx) (signedTx *Tx, inputsSigned []int, err error)

SignAuto goes through each input of the transaction and automatically signs the P2PKH inputs that it is able to sign using the specific PrivateKey passed in through the InternalSigner struct.

type Output

type Output struct {
	Satoshis      uint64
	LockingScript *bscript.Script
}

Output is a representation of a transaction output

func NewHashPuzzleOutput

func NewHashPuzzleOutput(secret, publicKeyHash string, satoshis uint64) (*Output, error)

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

func NewOpReturnOutput

func NewOpReturnOutput(data []byte) (*Output, error)

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

func NewOpReturnPartsOutput

func NewOpReturnPartsOutput(data [][]byte) (*Output, error)

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

func NewOutputFromBytes

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

NewOutputFromBytes returns a transaction Output from the bytes provided

func NewOutputFromReader added in v1.0.1

func NewOutputFromReader(r io.Reader) (*Output, error)

NewOutputFromReader returns a transaction Output from the io.Reader provided

func NewP2PKHOutputFromAddress

func NewP2PKHOutputFromAddress(addr string, satoshis uint64) (*Output, error)

NewP2PKHOutputFromAddress makes an output to a PKH with a value.

func NewP2PKHOutputFromPubKeyBytes

func NewP2PKHOutputFromPubKeyBytes(publicKeyBytes []byte, satoshis uint64) (*Output, error)

NewP2PKHOutputFromPubKeyBytes makes an output to a PKH with a value.

func NewP2PKHOutputFromPubKeyHashStr

func NewP2PKHOutputFromPubKeyHashStr(publicKeyHash string, satoshis uint64) (*Output, error)

NewP2PKHOutputFromPubKeyHashStr makes an output to a PKH with a value.

func NewP2PKHOutputFromPubKeyStr

func NewP2PKHOutputFromPubKeyStr(publicKey string, satoshis uint64) (*Output, error)

NewP2PKHOutputFromPubKeyStr makes an output to a PKH with a value.

func (*Output) GetBytesForSigHash

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

GetBytesForSigHash returns the proper serialization of an output to be hashed and signed (sighash).

func (*Output) GetLockingScriptHexString

func (o *Output) GetLockingScriptHexString() string

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

func (*Output) String

func (o *Output) String() string

func (*Output) ToBytes

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

ToBytes encodes the Output into a byte array.

type Signer

type Signer interface {
	Sign(index uint32, unsignedTx *Tx) (signedTx *Tx, err error)
	SignAuto(unsignedTx *Tx) (signedTx *Tx, inputsSigned []int, err error)
}

Signer interface to allow custom implementations of different signing mechanisms. Implement the Sign function as shown in InternalSigner, for example. Sign function takes an unsigned Tx and returns a signed Tx.

type Tx

type Tx struct {
	// TODO: make variables private?
	Inputs   []*Input
	Outputs  []*Output
	Version  uint32
	LockTime uint32
}

Tx wraps a bitcoin transaction

DO NOT CHANGE ORDER - Optimized 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 NewTxFromReader added in v1.0.1

func NewTxFromReader(r io.Reader) (*Tx, error)

NewTxFromReader creates a transaction from an io.Reader

func NewTxFromStream

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

NewTxFromStream takes an array of bytes and contructs 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) AddInput

func (tx *Tx) AddInput(input *Input)

AddInput adds a new input to the transaction.

func (*Tx) AddInputFromTx added in v0.0.8

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

AddInputFromTx take all outputs from previous transaction that match a specific public key, add it as input to this new transaction.

func (*Tx) AddOutput

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

AddOutput adds a new output to the transaction.

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) CalculateFee added in v0.0.11

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) ChangeToOutput added in v0.0.11

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

ChangeToOutput 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(txID string, vout uint32, prevTxLockingScript string, satoshis uint64) error

From adds a new input to the transaction from the specified UTXO fields.

func (*Tx) GetInputPreimage added in v0.0.7

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

GetInputPreimage serializes the transaction based on the input index and the SIGHASH flag see https://github.com/bitcoin-sv/bitcoin-sv/blob/master/doc/abc/replay-protected-sighash.md#digest-algorithm

func (*Tx) GetInputSignatureHash

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

GetInputSignatureHash gets the preimage of the specified input and hashes it.

func (*Tx) GetInputs

func (tx *Tx) GetInputs() []*Input

GetInputs returns an array of all inputs in the transaction.

func (*Tx) GetOutputs

func (tx *Tx) GetOutputs() []*Output

GetOutputs returns an array of all outputs in the transaction.

func (*Tx) GetTotalInputSatoshis

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

GetTotalInputSatoshis returns the total Satoshis inputted to the transaction.

func (*Tx) GetTotalOutputSatoshis

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

GetTotalOutputSatoshis returns the total Satoshis outputted from the transaction.

func (*Tx) GetTxID

func (tx *Tx) GetTxID() string

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

func (*Tx) GetTxIDAsBytes added in v0.0.8

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

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

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) HasOutputsWithAddress added in v1.0.0

func (tx *Tx) HasOutputsWithAddress(addr string) ([]int, bool, error)

HasOutputsWithAddress will return the index of any outputs found matching the address 'addr'.

bool will be false if none have been found. err will not be nil if the addr is not a valid P2PKH address.

func (*Tx) HasOutputsWithScript added in v1.0.0

func (tx *Tx) HasOutputsWithScript(s *bscript.Script) ([]int, bool)

HasOutputsWithScript will return the index of any outputs found matching the locking script 's'.

bool will be false if none have been found.

func (*Tx) InputCount

func (tx *Tx) InputCount() int

InputCount returns the number of transaction inputs.

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

func (tx *Tx) OutputCount() int

OutputCount returns the number of transaction inputs.

func (*Tx) PayTo

func (tx *Tx) PayTo(addr string, 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) Sign

func (tx *Tx) Sign(index uint32, s Signer) 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.

func (*Tx) SignAuto

func (tx *Tx) SignAuto(s Signer) (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) ToBytes

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

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

func (*Tx) ToBytesWithClearedInputs

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

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

func (*Tx) ToString

func (tx *Tx) ToString() string

ToString encodes the transaction into a hex string.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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