bt

package module
v2.7.4 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: ISC Imports: 19 Imported by: 58

README ΒΆ

πŸ› οΈΒ Β go-bt

The go-to Bitcoin Transaction (BT) GoLang library

Forked from libsv/go-bt


Release Go Version License


CI / CD Β Β  Build Last Commit Β Β Β Β  Quality Β Β  Coverage
Security Β Β  Scorecard Security Β Β Β Β  Community Β Β  Contributors Ask DeepWiki


Project Navigation
πŸ“¦Β Installation πŸ§ͺΒ ExamplesΒ &Β Tests πŸ“šΒ Documentation
🀝 Contributing πŸ› οΈΒ CodeΒ Standards ⚑ Benchmarks
πŸ€–Β AIΒ Usage πŸ“Β License πŸ‘₯Β Maintainers

🧩 What's Inside

  • Full-featured Bitcoin transactions and transaction manipulation/functionality
  • Auto-fee calculations for change outputs
  • Transaction fee calculation and related checks
  • Interfaced signing/unlocking of transaction inputs for easy adaptation/customization and extendability for any use case
  • Bitcoin Transaction Script functionality
    • Bitcoin script engine (interpreter)
    • P2PKH (base58 addresses)
    • Data (OP_RETURN)
    • BIP276

πŸ“¦ Installation

go-bt requires a supported release of Go.

go get -u github.com/bsv-blockchain/go-bt/v2

πŸ“š Documentation

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


Development Build Commands

Get the MAGE-X build tool for development:

go install github.com/mrz1836/mage-x/cmd/magex@latest

View all build commands

magex help
Repository Features

This repository includes 25+ built-in features covering CI/CD, security, code quality, developer experience, and community tooling.

View the full Repository Features list β†’

Library Deployment

This project uses goreleaser for streamlined binary and library deployment to GitHub. To get started, install it via:

brew install goreleaser

The release process is defined in the .goreleaser.yml configuration file.

Then create and push a new Git tag using:

magex version:bump push=true bump=patch branch=master

This process ensures consistent, repeatable releases with properly versioned artifacts and citation metadata.

Pre-commit Hooks

Set up the Go-Pre-commit System to run the same formatting, linting, and tests defined in AGENTS.md before every commit:

go install github.com/mrz1836/go-pre-commit/cmd/go-pre-commit@latest
go-pre-commit install

The system is configured via modular env files in .github/env/ and provides 17x faster execution than traditional Python-based pre-commit hooks. See the complete documentation for details.

GitHub Workflows

All workflows are driven by modular configuration in .github/env/ β€” no YAML editing required.

View all workflows and the control center β†’

Updating Dependencies

To update all dependencies (Go modules, linters, and related tools), run:

magex deps:update

This command ensures all dependencies are brought up to date in a single step, including Go modules and any tools managed by MAGE-X. It is the recommended way to keep your development environment and CI in sync with the latest versions.


πŸ§ͺ Examples & Tests

All unit tests and examples run via GitHub Actions and use Go version 1.26.x. View the configuration file.

Run all tests (fast):

magex test

Run all tests with race detector (slower):

magex test:race

⚑ Benchmarks

Run the Go benchmarks:

magex bench

Benchmark Results
Benchmark Iterations ns/op B/op allocs/op
[Bytes]-toBytesHelper 4,112,503 280.2 1024 1
[Clone]-clone 4,117,903 291.4 416 13
[ShallowClone]-clone 5,963,280 196.3 296 8

These benchmarks reflect fast, allocation-free lookups for most retrieval functions, ensuring optimal performance in production environments. Performance benchmarks for the core functions in this library, executed on an Apple M1 Max (ARM64).


πŸ› οΈ Code Standards

Read more about this Go project's code standards.


πŸ€– AI Usage & Assistant Guidelines

Read the AI Usage & Assistant Guidelines for details on how AI is used in this project and how to interact with AI assistants.


πŸ‘₯ Maintainers

Siggi Galt MrZ
Siggi Dylan 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 πŸ’¬.

Stars


πŸ“ License

License

Documentation ΒΆ

Overview ΒΆ

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

Index ΒΆ

Constants ΒΆ

View Source
const (
	// MaxTxInSequenceNum is the maximum sequence number the sequence field
	// of a transaction input can be.
	MaxTxInSequenceNum uint32 = 0xffffffff

	// MaxPrevOutIndex is the maximum index the index field of a previous
	// outpoint can be.
	MaxPrevOutIndex uint32 = 0xffffffff

	// SequenceLockTimeDisabled is a flag that if set on a transaction
	// input's sequence number, the sequence number will not be interpreted
	// as a relative locktime.
	SequenceLockTimeDisabled = 1 << 31

	// SequenceLockTimeIsSeconds is a flag that if set on a transaction
	// input's sequence number, the relative locktime has units of 512
	// seconds.
	SequenceLockTimeIsSeconds = 1 << 22

	// SequenceLockTimeMask is a mask that extracts the relative locktime
	// when masked against the transaction input sequence number.
	SequenceLockTimeMask = 0x0000ffff
)
View Source
const DefaultSequenceNumber uint32 = 0xFFFFFFFF

DefaultSequenceNumber is the default starting sequence number

View Source
const (
	// DustLimit is the current minimum txo output accepted by miners.
	DustLimit = 1
)
View Source
const MaxArenaAlloc = 1 << 30

MaxArenaAlloc is the maximum single allocation size accepted by Arena.Alloc and by *.ReadFromWithArena script-length guards. Set to 1 GiB to admit legitimate large BSV transactions (e.g. ~320 MB data carriers) while still rejecting obviously-bogus varint lengths.

Implementation note: Arena.Alloc computes `a.pos + n` as int. With MaxArenaAlloc = 1<<30 and a 32-bit int, `pos + n` could overflow into negative values and bypass the grow check. go-bt targets 64-bit Go (all supported BSV node deployments are 64-bit); 32-bit platforms are not supported.

View Source
const OrdinalsPrefix = "ord"

OrdinalsPrefix contains 'ORD' the inscription protocol prefix.

Check the docs here: https://docs.1satordinals.com/

Variables ΒΆ

View Source
var (
	ErrInvalidTxID       = errors.New("invalid TxID")
	ErrTxNil             = errors.New("tx is nil")
	ErrTxTooShort        = errors.New("too short to be a tx - even an empty tx has 10 bytes")
	ErrNLockTimeLength   = errors.New("nLockTime length must be 4 bytes long")
	ErrEmptyValues       = errors.New("empty value or values passed, all arguments are required and cannot be empty")
	ErrUnsupportedScript = errors.New("non-P2PKH input used in the tx - unsupported")
	ErrInvalidScriptType = errors.New("invalid script type")
	ErrNoUnlocker        = errors.New("unlocker not supplied")

	// ErrTxTooLarge is returned by the bounded serializers (ExtendedBytesMax,
	// SerializeBytesMax) when the serialized size would exceed the caller-supplied
	// limit. Match it with errors.Is.
	ErrTxTooLarge = errors.New("serialized transaction exceeds size limit")
)

General errors.

View Source
var (
	ErrInputNoExist  = errors.New("specified input does not exist")
	ErrInputTooShort = errors.New("input length too short")

	// ErrInputSatsZero is returned when the input Satoshi value is not provided.
	ErrInputSatsZero = errors.New("input satoshi value is not provided")
)

Sentinel errors reported by inputs.

View Source
var (
	ErrOutputNoExist  = errors.New("specified output does not exist")
	ErrOutputTooShort = errors.New("output length too short")
)

Sentinel errors reported by outputs.

View Source
var (
	ErrEmptyPreviousTxID     = errors.New("'PreviousTxID' not supplied")
	ErrEmptyPreviousTxScript = errors.New("'PreviousTxScript' not supplied")
)

Sentinel errors reported by signature hash.

View Source
var (
	ErrFeeQuotesNotInit = errors.New("feeQuotes have not been setup, call NewFeeQuotes")
	ErrMinerNoQuotes    = errors.New("miner has no quotes stored")
	ErrFeeTypeNotFound  = errors.New("feetype not found")
	ErrFeeQuoteNotInit  = errors.New("feeQuote has not been initialized, call NewFeeQuote()")
	ErrUnknownFeeType   = errors.New("unknown fee type")
)

Sentinel errors reported by the fees.

View Source
var (
	// ErrNoUTXO signals the UTXOGetterFunc has reached the end of its input.
	ErrNoUTXO = errors.New("no remaining utxos")

	// ErrInsufficientFunds insufficient funds provided for funding
	ErrInsufficientFunds = errors.New("insufficient funds provided")
)

Sentinel errors reported by the Fund.

View Source
var (
	ErrDummyInput            = errors.New("failed to add dummy input 0")
	ErrInsufficientUTXOs     = errors.New("need at least 2 utxos")
	ErrInsufficientUTXOValue = errors.New("need at least 1 utxos which is > ordinal price")
	ErrUTXOInputMismatch     = errors.New("utxo and input mismatch")
	ErrInvalidSellOffer      = errors.New("invalid sell offer (partially signed tx)")
	ErrEmptyScripts          = errors.New("at least one of needed scripts is empty")
	ErrInsufficientFees      = errors.New("fee paid not enough with new locking script")
	ErrUnlockerNotFound      = errors.New("UTXO unlocker not found")
)

Sentinel errors reported by PSBTs.

View Source
var (

	// ErrInsufficientInputs is returned when the total inputted satoshis are less than the outputted satoshis.
	ErrInsufficientInputs = errors.New("satoshis inputted to the tx are less than the outputted satoshis")
)

Sentinel errors reported by change.

View Source
var (
	// ErrNonMinimalVarInt is returned when a CompactSize (VarInt) prefix is not
	// written in its shortest form, e.g. the value 1 encoded as `fd 01 00`
	// rather than `01`. Bitcoin and SV Node reject such an encoding at parse.
	ErrNonMinimalVarInt = errors.New("non-minimal varint encoding")
)

Sentinel errors reported when decoding variable length integers.

View Source
var (
	// ErrOutputsNotEmpty is returned when the transaction outputs are not empty
	ErrOutputsNotEmpty = errors.New("transaction outputs must be empty to avoid messing with Ordinal ordering scheme")
)

Sentinel errors reported by ordinal inscriptions.

Functions ΒΆ

func IsValidTxID ΒΆ

func IsValidTxID(txid *chainhash.Hash) bool

IsValidTxID will check that the txid bytes are valid.

A txid should be of 32 bytes length.

func LittleEndianBytes ΒΆ

func LittleEndianBytes(v, 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.

Types ΒΆ

type Arena ΒΆ added in v2.6.4

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

Arena is a bump-pointer allocator used by *.ReadFromWithArena to amortize per-script []byte allocations across a batch of transaction decodes.

All slices returned by Alloc remain valid until Reset (or ResetAndShrink) is called. The caller must not retain any slice returned by Alloc past a Reset call β€” the backing array will be reused for subsequent allocations.

Arena is NOT safe for concurrent use. A single goroutine must own the Arena between Reset calls.

The zero value Arena{} is ready to use; the first Alloc allocates the backing slab.

func NewArena ΒΆ added in v2.6.4

func NewArena(initialCap int) *Arena

NewArena returns an Arena with initialCap bytes pre-allocated. Passing initialCap <= 0 is equivalent to using a zero-value Arena.

func (*Arena) Alloc ΒΆ added in v2.6.4

func (a *Arena) Alloc(n int) []byte

Alloc returns a slice of length n drawn from the arena's slab. The returned slice has cap == len (3-arg slicing) so writes cannot overflow into subsequent allocations.

Panics if n < 0 or n > MaxArenaAlloc.

func (*Arena) Cap ΒΆ added in v2.6.4

func (a *Arena) Cap() int

Cap returns the current backing slab capacity.

func (*Arena) Reset ΒΆ added in v2.6.4

func (a *Arena) Reset()

Reset rewinds the arena's cursor to 0. The current backing slab is retained for reuse. O(1).

Lifetime contract: any slice returned by Alloc that was allocated from the CURRENT slab becomes invalid for future reads after Reset β€” the backing memory will be overwritten by subsequent Alloc calls. Slices returned from an OLDER slab (i.e. before the most recent grow event) remain readable for as long as a caller holds a reference β€” the older slabs are not overwritten, they are simply orphaned for GC. Repeated grow-then-reset cycles can therefore retain pre-grow allocations longer than callers expect; use ResetAndShrink to drop oversized slabs explicitly.

func (*Arena) ResetAndShrink ΒΆ added in v2.6.4

func (a *Arena) ResetAndShrink(maxKeep int)

ResetAndShrink behaves like Reset but additionally drops the backing slab if its capacity exceeds maxKeep. Use to bound the idle footprint of a pooled arena when a recent decode required an unusually large allocation. Passing maxKeep <= 0 retains the slab unchanged.

func (*Arena) Used ΒΆ added in v2.6.4

func (a *Arena) Used() int

Used returns the number of bytes currently allocated since the last Reset.

type ExtendedTx ΒΆ

type ExtendedTx struct {
	*Tx
}

ExtendedTx wraps a *bt.Tx and provides a method to convert it back to *bt.Tx.

func (*ExtendedTx) ToTx ΒΆ

func (etx *ExtendedTx) ToTx() *Tx

ToTx returns the underlying *bt.Tx from the ExtendedTx.

type Fee ΒΆ

type Fee struct {
	FeeType   FeeType `json:"-"` // 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

type FeeQuote ΒΆ

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

FeeQuote contains a thread safe map of fees for standard and data fees as well as an expiry time for a specific miner.

This can be used if you are only dealing with a single miner and know you will always be using a single miner. FeeQuote will store the fees for a single miner and can be passed to transactions to calculate fees when creating change outputs.

If you are dealing with quotes from multiple miners, use the FeeQuotes structure above.

NewFeeQuote() should be called to get a new instance of a FeeQuote.

When expiry expires ie Expired() == true then you should fetch new quotes from a MAPI server and call AddQuote with the fee information.

func NewFeeQuote ΒΆ

func NewFeeQuote() *FeeQuote

NewFeeQuote will set up and return a new FeeQuotes struct which contains default fees when initially setup. You would then pass this data structure to a singleton struct via injection for reading. If you are only getting quotes from one miner, you can use this directly instead of using the NewFeeQuotes() method which is for storing multiple miner quotes.

fq := NewFeeQuote()

The fees have an expiry time which, when initially setup, has expiry of now.UTC. This allows you to check for fq.Expired() and if true fetch a new set of fees from a MAPI server. This means the first check will always fetch the latest fees. If you want to just use default fees always, you can ignore the expired method and simply call the fq.Fee() method. https://github.com/bitcoin-sv-specs/brfc-merchantapi#payload

A basic example of usage is shown below:

func Fee(ft bt.FeeType) *bt.Fee{
   // you would not call this every time - this is just an example
   // you'd call this at app startup and store it / pass to a struct
   fq := NewFeeQuote()

   // fq setup with defaultFees
   if !fq.Expired() {
      // not expired, just return fee we have cached
      return fe.Fee(ft)
   }

   // cache expired, fetch new quotes
   var stdFee *bt.Fee
   var dataFee *bt.Fee

   // fetch quotes from MAPI server

   fq.AddQuote(bt.FeeTypeStandard, stdFee)
   fq.AddQuote(bt.FeeTypeData, dataFee)

   // MAPI returns a quote expiry
   exp, _ := time.Parse(time.RFC3339, resp.Quote.ExpirationTime)
   fq.UpdateExpiry(exp)
   return fe.Fee(ft)
}

It will set the expiry time to now.UTC which when expires will indicate that new quotes should be fetched from a MAPI server.

func (*FeeQuote) AddQuote ΒΆ

func (f *FeeQuote) AddQuote(ft FeeType, fee *Fee) *FeeQuote

AddQuote will add a new set of quotes for a feetype or update an existing quote if it already exists.

func (*FeeQuote) Expired ΒΆ

func (f *FeeQuote) Expired() bool

Expired will return true if the expiry time is before UTC now, this means we need to fetch fresh quotes from a MAPI server.

func (*FeeQuote) Expiry ΒΆ

func (f *FeeQuote) Expiry() time.Time

Expiry will return the expiry timestamp for the `bt.FeeQuote` in a threadsafe manner.

func (*FeeQuote) Fee ΒΆ

func (f *FeeQuote) Fee(t FeeType) (*Fee, error)

Fee will return a fee by type if found, nil and an error if not.

func (*FeeQuote) MarshalJSON ΒΆ

func (f *FeeQuote) MarshalJSON() ([]byte, error)

MarshalJSON will convert the FeeQuote to a json object with the format as shown:

 {
	 "data": {
		 "miningFee": {
			 "satoshis": 5,
			 "bytes": 2
		 },
		 "relayFee": {
			 "satoshis": 8,
			 "bytes": 4
		 }
	 },
	 "standard": {
		 "miningFee": {
			 "satoshis": 100,
			 "bytes": 10
		 },
		 "relayFee": {
			 "satoshis": 10,
			 "bytes": 5
		 }
	 }
 }

func (*FeeQuote) UnmarshalJSON ΒΆ

func (f *FeeQuote) UnmarshalJSON(body []byte) error

UnmarshalJSON will convert a JSON encoded FeeQuote back into a fee quote type, the expected JSON format is shown above in the MarshalJSON function. If the fee type supplied is unknown, an ErrUnknownFeeType will be returned.

func (*FeeQuote) UpdateExpiry ΒΆ

func (f *FeeQuote) UpdateExpiry(exp time.Time)

UpdateExpiry will update the expiry time of the quotes, this will be used when you fetch a fresh set of quotes from a MAPI server which should return an expiration time.

type FeeQuotes ΒΆ

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

FeeQuotes contains a list of miners and the current fees for each miner as well as their expiry.

This can be used when getting fees from multiple miners, and you want to use the cheapest, for example.

Usage setup should be calling NewFeeQuotes(minerName).

func NewFeeQuotes ΒΆ

func NewFeeQuotes(minerName string) *FeeQuotes

NewFeeQuotes will set up default feeQuotes for the minerName supplied, i.e., TAAL etc.

func (*FeeQuotes) AddMiner ΒΆ

func (f *FeeQuotes) AddMiner(minerName string, quote *FeeQuote) *FeeQuotes

AddMiner will add a new miner to the quote map with the provided feeQuote. If you just want to add default fees, use the AddMinerWithDefault method.

func (*FeeQuotes) AddMinerWithDefault ΒΆ

func (f *FeeQuotes) AddMinerWithDefault(minerName string) *FeeQuotes

AddMinerWithDefault will add a new miner to the quotes map with default fees and immediate expiry.

func (*FeeQuotes) Fee ΒΆ

func (f *FeeQuotes) Fee(minerName string, feeType FeeType) (*Fee, error)

Fee is a convenience method for quickly getting a fee by type and miner name. If the miner has no fees, an ErrMinerNoQuotes error will be returned. If the feeType cannot be found, an ErrFeeTypeNotFound error will be returned.

func (*FeeQuotes) Quote ΒΆ

func (f *FeeQuotes) Quote(minerName string) (*FeeQuote, error)

Quote will return all fees for a miner. If no fees are found, an ErrMinerNoQuotes error is returned.

func (*FeeQuotes) UpdateMinerFees ΒΆ

func (f *FeeQuotes) UpdateMinerFees(minerName string, feeType FeeType, fee *Fee) (*FeeQuote, error)

UpdateMinerFees a convenience method to update a fee quote from a FeeQuotes struct directly. This will update the miner feeType with the provided fee. Useful after receiving new quotes from mapi.

type FeeType ΒΆ

type FeeType string

FeeType is used to specify which type of fee is used depending on the type of tx data (e.g.: 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 - Optimized for memory via maligned

func (*Input) Bytes ΒΆ

func (i *Input) Bytes(clearLockingScript bool, intoBytes ...[]byte) []byte

Bytes encodes the Input into a hex byte array.

func (*Input) ExtendedBytes ΒΆ

func (i *Input) ExtendedBytes(clearLockingScript bool, intoBytes ...[]byte) []byte

ExtendedBytes encodes the Input into a hex byte array, including the EF transaction format information.

func (*Input) ExtendedSize ΒΆ added in v2.7.2

func (i *Input) ExtendedSize() uint64

ExtendedSize returns the serialized size of the Input in extended format without allocating: the standard fields plus PreviousTxSatoshis and PreviousTxScript (with a zero-length prev script encoded as a single byte). It returns uint64 to compose safely into Tx.ExtendedSize, whose total can exceed what an int holds on a 32-bit platform.

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(txIDHash *chainhash.Hash) 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) PreviousTxIDChainHash ΒΆ

func (i *Input) PreviousTxIDChainHash() *chainhash.Hash

PreviousTxIDChainHash returns the PreviousTxID as a chainhash.Hash.

func (*Input) PreviousTxIDStr ΒΆ

func (i *Input) PreviousTxIDStr() string

PreviousTxIDStr returns the Previous TxID as a hex string.

func (*Input) ReadFrom ΒΆ

func (i *Input) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads from the `io.Reader` into the `bt.Input`.

func (*Input) ReadFromExtended ΒΆ

func (i *Input) ReadFromExtended(r io.Reader) (int64, error)

ReadFromExtended reads the `io.Reader` into the `bt.Input` when the reader is consuming an extended format transaction.

func (*Input) ReadFromExtendedWithArena ΒΆ added in v2.6.4

func (i *Input) ReadFromExtendedWithArena(r io.Reader, a *Arena) (int64, error)

ReadFromExtendedWithArena is the extended-format counterpart to ReadFromWithArena. The PreviousTxScript byte slice is also drawn from arena.

func (*Input) ReadFromWithArena ΒΆ added in v2.6.4

func (i *Input) ReadFromWithArena(r io.Reader, a *Arena) (int64, error)

ReadFromWithArena reads from r into i (standard format) drawing the unlocking-script []byte from arena. See bt.Arena for lifetime contract. Existing ReadFrom is unchanged.

func (*Input) Size ΒΆ added in v2.6.0

func (i *Input) Size() int

Size returns the serialized size of the Input in bytes without allocating.

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.

func (*Input) WriteExtendedTo ΒΆ added in v2.6.0

func (i *Input) WriteExtendedTo(w io.Writer) (int64, error)

WriteExtendedTo writes the serialized Input in extended format directly to w. Extended format appends PreviousTxSatoshis and PreviousTxScript after the standard input fields.

func (*Input) WriteTo ΒΆ added in v2.6.0

func (i *Input) WriteTo(w io.Writer) (int64, error)

WriteTo writes the serialized Input directly to w without allocating an intermediate byte slice. It writes the standard (non-extended) format.

type Output ΒΆ

type Output struct {
	Satoshis      uint64          `json:"satoshis"`
	LockingScript *bscript.Script `json:"locking_script"`
}

Output is a representation of a transaction output

func CreateOpReturnOutput ΒΆ

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

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

func (*Output) Bytes ΒΆ

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

Bytes encodes the Output into a byte array.

func (*Output) BytesForSigHash ΒΆ

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

BytesForSigHash returns the proper serialization 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 serialize an output to json.

func (*Output) NodeJSON ΒΆ

func (o *Output) NodeJSON() interface{}

NodeJSON returns a wrapped *bt.Output for marshaling/unmarshalling into a node output format.

Marshaling usage example:

bb, err := json.Marshal(output.NodeJSON())

Unmarshalling usage example:

output := &bt.Output{}
if err := json.Unmarshal(bb, output.NodeJSON()); err != nil {}

func (*Output) ReadFrom ΒΆ

func (o *Output) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads from the `io.Reader` into the `bt.Output`.

func (*Output) ReadFromWithArena ΒΆ added in v2.6.4

func (o *Output) ReadFromWithArena(r io.Reader, a *Arena) (int64, error)

ReadFromWithArena decodes an Output from r. When a is non-nil, the locking-script byte slice is drawn from the arena and remains valid only until the next arena.Reset or ResetAndShrink call. When a is nil, the locking script is heap-allocated via make([]byte, n) and there is no arena lifetime restriction β€” this nil-arena path is the implementation used by the standard (non-arena) Output.ReadFrom.

func (*Output) Size ΒΆ added in v2.6.0

func (o *Output) Size() int

Size returns the serialized size of the Output in bytes without allocating.

func (*Output) String ΒΆ

func (o *Output) String() string

func (*Output) UnmarshalJSON ΒΆ

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

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

func (*Output) WriteTo ΒΆ added in v2.6.0

func (o *Output) WriteTo(w io.Writer) (int64, error)

WriteTo writes the serialized Output directly to w without allocating an intermediate byte slice.

type SigHashCache ΒΆ added in v2.6.2

type SigHashCache struct {
	PrevOutHash  []byte
	SequenceHash []byte
	OutputsHash  []byte
}

SigHashCache holds pre-computed intermediate hash values used during signature hashing. When signing multiple inputs of the same transaction, these hashes are identical across inputs (for the common SighashAll case) and can be computed once instead of O(N) times.

Create with tx.NewSigHashCache() and pass to CalcInputPreimageWithCache.

type Tx ΒΆ

type Tx struct {
	Inputs   []*Input  `json:"inputs"`
	Outputs  []*Output `json:"outputs"`
	Version  uint32    `json:"version"`
	LockTime uint32    `json:"locktime"`
	// contains filtered or unexported fields
}

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 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 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) AddP2PKHOutputFromBip32ExtKey ΒΆ

func (tx *Tx) AddP2PKHOutputFromBip32ExtKey(privKey *bip32.ExtendedKey, satoshis uint64) (string, error)

AddP2PKHOutputFromBip32ExtKey generated a random P2PKH output script from a provided *bip32.ExtendedKey, and add it to the receiving tx. The derviation path used is returned.

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) AppendBytes ΒΆ added in v2.6.2

func (tx *Tx) AppendBytes(dst []byte) []byte

AppendBytes appends the serialized transaction to dst and returns the extended slice. When dst has sufficient capacity (e.g. pre-allocated via tx.Size()), this method performs zero heap allocations.

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 serializes 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) CalcInputPreimageLegacy ΒΆ

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

CalcInputPreimageLegacy serializes the transaction based on the input index and the SIGHASH flag and returns the preimage before double hashing (SHA256d), in the legacy format.

see https://wiki.bitcoinsv.io/index.php/Legacy_Sighash_Algorithm

func (*Tx) CalcInputPreimageWithCache ΒΆ added in v2.6.2

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

CalcInputPreimageWithCache is like CalcInputPreimage but uses pre-computed hashes from a SigHashCache. Use this when signing multiple inputs to avoid redundant O(N) hash computations per input.

func (*Tx) CalcInputSignatureHash ΒΆ

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

CalcInputSignatureHash serialized 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) Change ΒΆ

func (tx *Tx) Change(s *bscript.Script, f *FeeQuote) error

Change calculates the number of fees needed to cover the transaction

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

func (*Tx) ChangeToAddress ΒΆ

func (tx *Tx) ChangeToAddress(addr string, f *FeeQuote) error

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

func (*Tx) ChangeToExistingOutput ΒΆ

func (tx *Tx) ChangeToExistingOutput(index uint, f *FeeQuote) 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) Clone ΒΆ

func (tx *Tx) Clone() *Tx

Clone returns a clone of the tx

func (*Tx) CloneTx ΒΆ

func (tx *Tx) CloneTx() *Tx

CloneTx returns a clone of the tx by bytes

func (*Tx) EstimateFeesPaid ΒΆ

func (tx *Tx) EstimateFeesPaid(fees *FeeQuote) (*TxFees, error)

EstimateFeesPaid will estimate how big the tx will be when finalized by estimating input unlocking scripts that have not yet been filled including the individual fee types (std/data/etc.).

func (*Tx) EstimateIsFeePaidEnough ΒΆ

func (tx *Tx) EstimateIsFeePaidEnough(fees *FeeQuote) (bool, error)

EstimateIsFeePaidEnough will calculate the fees that this transaction is paying including the individual fee types (std/data/etc.), and will add 107 bytes to the unlocking script of any unsigned inputs (only P2PKH for now) found to give a final size estimate of the tx size for fee calculation.

func (*Tx) EstimateSize ΒΆ

func (tx *Tx) EstimateSize() (int, error)

EstimateSize will return the size of tx in bytes and will add 107 bytes to the unlocking script of any unsigned inputs (only P2PKH for now) found to give a final size estimate of the tx size.

func (*Tx) EstimateSizeWithTypes ΒΆ

func (tx *Tx) EstimateSizeWithTypes() (*TxSize, error)

EstimateSizeWithTypes will return the size of tx in bytes, including the different data types (std/data/etc.), and will add 107 bytes to the unlocking script of any unsigned inputs (only P2PKH for now) found to give a final size estimate of the tx size.

func (*Tx) ExtendedBytes ΒΆ

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

ExtendedBytes outputs the transaction into a byte array in extended format (with PreviousTxSatoshis and PreviousTXScript included)

func (*Tx) ExtendedBytesMax ΒΆ added in v2.7.2

func (tx *Tx) ExtendedBytesMax(limit uint64) ([]byte, error)

ExtendedBytesMax behaves like ExtendedBytes but refuses to allocate a representation larger than limit bytes. When the extended size exceeds limit it returns an error wrapping ErrTxTooLarge (matchable with errors.Is) and does not allocate the representation, letting a caller reject or reroute an oversized transaction before it materializes in memory. A limit equal to the extended size is allowed.

func (*Tx) ExtendedSize ΒΆ added in v2.7.2

func (tx *Tx) ExtendedSize() uint64

ExtendedSize returns the size in bytes of the transaction serialized in extended format - the representation produced by ExtendedBytes and WriteExtendedTo, which carries the marker plus every spent output's satoshis and locking script. It is computed from the structure fields without allocating, and always reflects the extended shape regardless of whether IsExtended reports true.

It returns uint64 (unlike Size, which returns int) because a consensus-valid transaction's extended representation can exceed what an int holds on a 32-bit platform and can exceed 2^31 anywhere; a caller can compare it against a resource budget and reject or reroute an oversized transaction before allocating. See ExtendedBytesMax for a helper that does exactly that.

func (*Tx) FillAllInputs ΒΆ

func (tx *Tx) FillAllInputs(ctx context.Context, ug UnlockerGetter) error

FillAllInputs is used to sign all inputs. It takes an UnlockerGetter interface as a parameter so that different unlocking implementations can be used to sign the transaction - for example local/external signing, or P2PKH/contract signing.

Given this signs inputs and outputs, sighash `ALL|FORKID` is used.

func (*Tx) FillInput ΒΆ

func (tx *Tx) FillInput(ctx context.Context, unlocker Unlocker, params UnlockerParams) error

FillInput is used to unlock the transaction at a specific input index. It takes an Unlocker interface as a parameter so that different unlocking implementations can be used to unlock the transaction - for example local or external unlocking (hardware wallet), or signature / non-signature based.

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 finalized sequence number (0xFFFFFFFF). If you want a different nSeq, change it manually afterward.

func (*Tx) FromUTXOs ΒΆ

func (tx *Tx) FromUTXOs(utxos ...*UTXO) error

FromUTXOs adds a new input to the transaction from the specified *bt.UTXO fields, using the default finalized sequence number (0xFFFFFFFF). If you want a different nSeq, change it manually afterward.

func (*Tx) Fund ΒΆ

func (tx *Tx) Fund(ctx context.Context, fq *FeeQuote, next UTXOGetterFunc) error

Fund continuously calls the provided bt.UTXOGetterFunc, adding each returned input as an input via tx.From(...), until it is estimated that inputs cover the outputs + fees.

After completion, the receiver is ready for `Change(...)` to be called, and then be signed. Important: this function works under the assumption that receiver *bt.Tx already has all the outputs which need covered.

If insufficient utxos are provided from the UTXOGetterFunc, a bt.ErrInsufficientFunds is returned.

Example usage:

if err := tx.Fund(ctx, bt.NewFeeQuote(), func(ctx context.Context, deficit satoshis) ([]*bt.UTXO, error) {
    utxos := make([]*bt.UTXO, 0)
    for _, f := range funds {
        deficit -= satoshis
        utxos := append(utxos, &bt.UTXO{
            TxID: f.TxID,
            Vout: f.Vout,
            LockingScript: f.Script,
            Satoshis: f.Satoshis,
        })
        if deficit == 0 {
            return utxos, nil
        }
    }
    return nil, bt.ErrNoUTXO
}); err != nil {
    if errors.Is(err, bt.ErrInsufficientFunds) { /* handle */ }
    return err
}

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) HashTxIDInto ΒΆ added in v2.6.4

func (tx *Tx) HashTxIDInto(scratch []byte) (chainhash.Hash, []byte)

HashTxIDInto computes the transaction's txid (double-SHA256 of the standard serialization), reusing the caller's scratch buffer for serialization. The returned scratch slice may share backing memory with the input β€” callers should always rebind it (h, scratch = tx.HashTxIDInto(scratch)).

If the transaction's hash has already been cached via SetTxHash, the scratch buffer is passed through unchanged and no allocation occurs. TxIDChainHash itself does not populate the cache; only SetTxHash does.

Allocations beyond the caller-owned scratch are zero (assuming scratch has sufficient capacity for tx.Size()).

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) Inscribe ΒΆ

func (tx *Tx) Inscribe(ia *bscript.InscriptionArgs) error

Inscribe adds an output to the transaction with an inscription.

func (*Tx) InscribeSpecificOrdinal ΒΆ

func (tx *Tx) InscribeSpecificOrdinal(ia *bscript.InscriptionArgs, inputIdx uint32, satoshiIdx uint64,
	extraOutputScript *bscript.Script,
) error

InscribeSpecificOrdinal gives you the functionality to choose a specific ordinal from the inputs to inscribe.

You need to provide the input and Satoshi range indices in order to specify the ordinal you would like to inscribe, along with the change addresses to be used for the rest of the Satoshis.

One output will be created with the extra Satoshis and then another output will be created with 1 Satoshi with the inscription in it.

func (*Tx) InsertInputUnlockingScript ΒΆ

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

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

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) IsExtended ΒΆ

func (tx *Tx) IsExtended() bool

IsExtended checks if the transaction is in extended format.

func (*Tx) IsFeePaidEnough ΒΆ

func (tx *Tx) IsFeePaidEnough(fees *FeeQuote) (bool, error)

IsFeePaidEnough will calculate the fees that this transaction is paying including the individual fee types (std/data/etc.).

func (*Tx) MarshalJSON ΒΆ

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

MarshalJSON will serialize a transaction to json.

func (*Tx) NewSigHashCache ΒΆ added in v2.6.2

func (tx *Tx) NewSigHashCache() *SigHashCache

NewSigHashCache pre-computes the intermediate hashes for the modern (post-fork) sighash algorithm. The returned cache can be passed to CalcInputPreimageWithCache for each input, avoiding O(NΒ²) work.

func (*Tx) NodeJSON ΒΆ

func (tx *Tx) NodeJSON() interface{}

NodeJSON returns a wrapped *bt.Tx for marshaling/unmarshalling into a node tx format.

Marshaling usage example:

bb, err := json.Marshal(tx.NodeJSON())

Unmarshalling usage example:

tx := bt.NewTx()
if err := json.Unmarshal(bb, tx.NodeJSON()); err != nil {}

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) OutputsHash ΒΆ

func (tx *Tx) OutputsHash(n int32) []byte

OutputsHash returns a bytes slice of the requested output, used for generating the txs signature hash. If n is -1, it will create the byte slice from all outputs.

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) PreviousOutHash ΒΆ

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

PreviousOutHash returns a byte slice of inputs outpoints, for creating a signature hash

func (*Tx) ReadFrom ΒΆ

func (tx *Tx) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads from the `io.Reader` into the `bt.Tx`.

func (*Tx) ReadFromWithArena ΒΆ added in v2.6.4

func (tx *Tx) ReadFromWithArena(r io.Reader, a *Arena) (int64, error)

ReadFromWithArena decodes a Tx from r. When a is non-nil, per-script byte slices (input UnlockingScript / PreviousTxScript, output LockingScript) are drawn from the arena; those slices remain valid only until the next arena.Reset or ResetAndShrink call. When a is nil, scripts are heap- allocated via make([]byte, n) and there is no arena lifetime restriction β€” this nil-arena path is the implementation used by the standard (non-arena) Tx.ReadFrom.

Tx field semantics (Version, LockTime, Inputs/Outputs slice headers) are identical to ReadFrom.

func (*Tx) SequenceHash ΒΆ

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

SequenceHash returns a byte slice of inputs SequenceNumber, for creating a signature hash

func (*Tx) SerializeBytes ΒΆ added in v2.4.4

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

SerializeBytes returns the serialized byte representation of the transaction. If the transaction is in extended format, it includes additional data such as PreviousTxSatoshis and PreviousTxScript.

func (*Tx) SerializeBytesMax ΒΆ added in v2.7.2

func (tx *Tx) SerializeBytesMax(limit uint64) ([]byte, error)

SerializeBytesMax behaves like SerializeBytes - extended format when the transaction is extended, otherwise standard - but refuses to allocate a representation larger than limit bytes, returning an error wrapping ErrTxTooLarge (matchable with errors.Is) instead. A limit equal to the serialized size is allowed.

func (*Tx) SerializeTo ΒΆ added in v2.6.0

func (tx *Tx) SerializeTo(w io.Writer) (int64, error)

SerializeTo writes the transaction to w using extended format if the transaction is extended, otherwise standard format. No intermediate byte slice is allocated.

func (*Tx) SetExtended ΒΆ

func (tx *Tx) SetExtended(extended bool)

SetExtended sets the extended flag for the transaction.

func (*Tx) SetTxHash ΒΆ

func (tx *Tx) SetTxHash(hash *chainhash.Hash)

SetTxHash should only be used when the transaction hash is known and the transaction will not change, this can be used to optimize processes that depend on the txid and avoid recalculating it

func (*Tx) ShallowClone ΒΆ

func (tx *Tx) ShallowClone() *Tx

ShallowClone returns a clone of the tx. Version, LockTime, and per-input fields used during signing are copied; script bytes are deep-copied so the clone is safe against arena resets and in-place mutation of script bytes.

Creating a new Tx from scratch is much faster than cloning from bytes (~420ns/op vs. ~2200ns/op); this matters as we clone txs a couple of times when verifying signatures.

func (*Tx) Size ΒΆ

func (tx *Tx) Size() int

Size will return the size of tx in bytes without serializing the transaction. This is a zero-allocation calculation based on the structure fields.

func (*Tx) SizeWithTypes ΒΆ

func (tx *Tx) SizeWithTypes() *TxSize

SizeWithTypes will return the size of tx in bytes and include the different data types (std/data/etc.).

func (*Tx) String ΒΆ

func (tx *Tx) String() string

String encodes the transaction into a hex string.

func (*Tx) ToExtendedTx ΒΆ

func (tx *Tx) ToExtendedTx() *ExtendedTx

ToExtendedTx converts the Tx to an ExtendedTx if it is already extended.

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 ΒΆ added in v2.3.3

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

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

func (*Tx) TxIDChainHash ΒΆ

func (tx *Tx) TxIDChainHash() *chainhash.Hash

TxIDChainHash returns the transaction ID as a chainhash.Hash.

func (*Tx) UnmarshalJSON ΒΆ

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

UnmarshalJSON will unmarshal a transaction that has been marshaled with this library.

func (*Tx) WriteExtendedTo ΒΆ added in v2.6.0

func (tx *Tx) WriteExtendedTo(w io.Writer) (int64, error)

WriteExtendedTo writes the serialized transaction directly to w in extended format (with PreviousTxSatoshis and PreviousTxScript) without allocating an intermediate byte slice.

func (*Tx) WriteTo ΒΆ added in v2.6.0

func (tx *Tx) WriteTo(w io.Writer) (int64, error)

WriteTo writes the serialized transaction directly to w in standard format without allocating an intermediate byte slice.

type TxFees ΒΆ

type TxFees struct {
	// TotalFeePaid is the total number of fees this tx will pay.
	TotalFeePaid uint64
	// StdFeePaid is the amount of fee to cover the standard inputs and outputs, etc.
	StdFeePaid uint64
	// DataFeePaid is the amount of fee to cover the op_return data outputs.
	DataFeePaid uint64
}

TxFees is returned when CalculateFee is called and contains a breakdown of the fees including the total and the size breakdown of the tx in bytes.

type TxSize ΒΆ

type TxSize struct {
	// TotalBytes are the number of bytes for the entire tx.
	TotalBytes uint64
	// TotalStdBytes are the number of bytes for the tx minus the data bytes.
	TotalStdBytes uint64
	// TotalDataBytes is the size in bytes of the op_return / data outputs.
	TotalDataBytes uint64
}

TxSize contains the size breakdown of a transaction including the breakdown of data bytes vs. standard bytes. This information can be used when calculating fees.

type Txs ΒΆ

type Txs []*Tx

Txs a collection of *bt.Tx.

func (*Txs) NodeJSON ΒΆ

func (tt *Txs) NodeJSON() interface{}

NodeJSON returns a wrapped bt.Txs for marshaling/unmarshalling into a node tx format.

Marshaling usage example:

bb, err := json.Marshal(txs.NodeJSON())

Unmarshalling usage example:

var txs bt.Txs
if err := json.Unmarshal(bb, txs.NodeJSON()); err != nil {}

func (*Txs) ReadFrom ΒΆ

func (tt *Txs) ReadFrom(r io.Reader) (int64, error)

ReadFrom txs from a block in a `bt.Txs`. This assumes a preceding varint detailing the total number of txs that the reader will provide.

type UTXO ΒΆ

type UTXO struct {
	TxIDHash       *chainhash.Hash `json:"txid"`
	Vout           uint32          `json:"vout"`
	LockingScript  *bscript.Script `json:"locking_script"`
	Satoshis       uint64          `json:"satoshis"`
	SequenceNumber uint32          `json:"sequence_number"`
	Unlocker       *Unlocker       `json:"-"`
}

UTXO an unspent transaction output, used for creating inputs

func (*UTXO) LockingScriptHexString ΒΆ

func (u *UTXO) LockingScriptHexString() string

LockingScriptHexString return the locking script in hex format.

func (*UTXO) MarshalJSON ΒΆ

func (u *UTXO) MarshalJSON() ([]byte, error)

MarshalJSON will serialize an utxo to JSON.

func (*UTXO) NodeJSON ΒΆ

func (u *UTXO) NodeJSON() interface{}

NodeJSON returns a wrapped *bt.UTXO for marshaling/unmarshaling into a node utxo format.

Marshaling usage example:

bb, err := json.Marshal(utxo.NodeJSON())

Unmarshalling usage example:

utxo := &bt.UTXO{}
if err := json.Unmarshal(bb, utxo.NodeJSON()); err != nil {}

func (*UTXO) TxIDStr ΒΆ

func (u *UTXO) TxIDStr() string

TxIDStr return the tx id as a string.

func (*UTXO) UnmarshalJSON ΒΆ

func (u *UTXO) UnmarshalJSON(body []byte) error

UnmarshalJSON will convert a JSON serialized utxo to a bt.UTXO.

type UTXOGetterFunc ΒΆ

type UTXOGetterFunc func(ctx context.Context, deficit uint64) ([]*UTXO, error)

UTXOGetterFunc is used for tx.Fund(...). It provides the amount of satoshis required for funding as `deficit`, and expects []*bt.UTXO to be returned containing utxos of which *bt.Input's can be built. If the returned []*bt.UTXO does not cover the deficit after fee recalculation, then this UTXOGetterFunc is called again, with the newly calculated deficit passed in.

It is expected that bt.ErrNoUTXO will be returned once the utxo source is depleted.

type UTXOs ΒΆ

type UTXOs []*UTXO

UTXOs a collection of *bt.UTXO.

func (*UTXOs) NodeJSON ΒΆ

func (u *UTXOs) NodeJSON() interface{}

NodeJSON returns a wrapped bt.UTXOs for marshaling/unmarshalling into a node utxo format.

Marshaling usage example:

bb, err := json.Marshal(utxos.NodeJSON())

Unmarshalling usage example:

var txs bt.UTXOs
if err := json.Unmarshal(bb, utxos.NodeJSON()); err != nil {}

type Unlocker ΒΆ

type Unlocker interface {
	UnlockingScript(ctx context.Context, tx *Tx, up UnlockerParams) (uscript *bscript.Script, err error)
}

Unlocker interface to allow custom implementations of different unlocking mechanisms. Implement the Unlocker function as shown in LocalUnlocker, for example.

type UnlockerGetter ΒΆ

type UnlockerGetter interface {
	Unlocker(ctx context.Context, lockingScript *bscript.Script) (Unlocker, error)
}

UnlockerGetter interfaces getting an unlocker for a given output/locking script.

type UnlockerParams ΒΆ

type UnlockerParams struct {
	// InputIdx the input to be unlocked. [DEFAULT 0]
	InputIdx uint32
	// SigHashFlags the be applied [DEFAULT ALL|FORKID]
	SigHashFlags sighash.Flag
}

UnlockerParams params used for unlocking an input with a `bt.Unlocker`.

type VarInt ΒΆ

type VarInt uint64

VarInt (variable integer) is a field used in transaction data to indicate the number of upcoming fields, or the length of an upcoming field. See http://learnmeabitcoin.com/glossary/varint

func NewVarIntFromBytes ΒΆ

func NewVarIntFromBytes(bb []byte) (VarInt, int)

NewVarIntFromBytes 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

This function does NOT enforce minimal encoding: `fd 00 00` decodes to 0 here, whereas (*VarInt).ReadFrom rejects it with ErrNonMinimalVarInt. The leniency is retained only because the (VarInt, int) signature has no error return, so rejecting would be a breaking API change; it is not a statement that the encoding is valid. Nothing on a transaction parse path uses this function β€” every count and length prefix is read through ReadFrom.

Use (*VarInt).ReadFrom for anything decoding untrusted bytes.

func (VarInt) AppendTo ΒΆ added in v2.6.2

func (v VarInt) AppendTo(dst []byte) []byte

AppendTo appends the VarInt encoding to dst and returns the extended slice. It never allocates when dst has sufficient capacity.

func (VarInt) Bytes ΒΆ

func (v VarInt) Bytes() []byte

Bytes take the underlying unsigned integer and return a byte array in VarInt format. See http://learnmeabitcoin.com/glossary/varint

func (VarInt) Length ΒΆ

func (v VarInt) Length() int

Length return the length of the underlying byte representation of the `bt.VarInt`.

func (*VarInt) ReadFrom ΒΆ

func (v *VarInt) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads the next varint from the io.Reader and assigned it to itself.

A non-minimally encoded varint is rejected with ErrNonMinimalVarInt. Bitcoin and SV Node treat an over-long CompactSize prefix as a hard parse error, and accepting one here is worse than merely lenient: the over-long form decodes to the same value and is then RE-SERIALIZED canonically, so the resulting transaction has the canonical txid and every hash-based check downstream passes. Consumers cannot detect after the fact what they accepted, which makes the parse the only place the divergence is visible. Sibling readers in this ecosystem already enforce this β€” see go-wire's ReadVarInt.

func (VarInt) UpperLimitInc ΒΆ

func (v VarInt) UpperLimitInc() int

UpperLimitInc 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 increased if the length

is incremented. -1 will be returned when the upper limit

of VarInt is reached.

func (VarInt) WriteTo ΒΆ added in v2.6.0

func (v VarInt) WriteTo(w io.Writer) (int64, error)

WriteTo writes the VarInt to w without allocating.

Directories ΒΆ

Path Synopsis
Package bscript comment
Package bscript comment
interpreter
Package interpreter implements the bitcoin transaction script language.
Package interpreter implements the bitcoin transaction script language.
interpreter/debug
Package debug comment
Package debug comment
interpreter/errs
Package errs comment
Package errs comment
interpreter/scriptflag
Package scriptflag comment
Package scriptflag comment
Package chainhash provides a type for representing hashes used in the Bitcoin protocol and provides functions for working with them.
Package chainhash provides a type for representing hashes used in the Bitcoin protocol and provides functions for working with them.
examples
create_ordinal_bid command
Package main demonstrates how to create a bid for an ordinal inscription using the go-bt library.
Package main demonstrates how to create a bid for an ordinal inscription using the go-bt library.
create_tx command
Package main demonstrates how to create a transaction using the go-bt library.
Package main demonstrates how to create a transaction using the go-bt library.
create_tx_with_inscription command
Package main demonstrates how to create a transaction with an inscription using the go-bt library.
Package main demonstrates how to create a transaction with an inscription using the go-bt library.
create_tx_with_opreturn command
Package main demonstrates how to create a transaction with an OP_RETURN output using the go-bt library.
Package main demonstrates how to create a transaction with an OP_RETURN output using the go-bt library.
marshal_node_list command
Package main demonstrates how to marshal a list of transactions into a Node JSON format using the go-bt library.
Package main demonstrates how to marshal a list of transactions into a Node JSON format using the go-bt library.
marshal_node_tx command
Package main demonstrates how to marshal a single transaction into a Node JSON format using the go-bt library.
Package main demonstrates how to marshal a single transaction into a Node JSON format using the go-bt library.
read_txs_from_block command
Package main demonstrates how to read transactions from a block file in a memory-efficient way using the go-bt library.
Package main demonstrates how to read transactions from a block file in a memory-efficient way using the go-bt library.
unlocker_getter command
Package main demonstrates how to implement a custom `bt.UnlockerGetter`
Package main demonstrates how to implement a custom `bt.UnlockerGetter`
unmarshal_node_list command
Package main demonstrates how to unmarshal a list of transactions from Node JSON format using the go-bt library.
Package main demonstrates how to unmarshal a list of transactions from Node JSON format using the go-bt library.
unmarshal_node_tx command
Package main demonstrates how to unmarshal a transaction from Node JSON format using the go-bt library.
Package main demonstrates how to unmarshal a transaction from Node JSON format using the go-bt library.
Package ord provides a simple example using the ordinals protocol
Package ord provides a simple example using the ordinals protocol
Package sighash comment
Package sighash comment
testing
data
Package data comment
Package data comment
Package unlocker comment
Package unlocker comment

Jump to

Keyboard shortcuts

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