Documentation
ΒΆ
Overview ΒΆ
Package bt provides functions needed to create and manipulate Bitcoin transactions.
Index ΒΆ
- Constants
- Variables
- func IsValidTxID(txid *chainhash.Hash) bool
- func LittleEndianBytes(v uint32, l uint32) []byte
- func ReverseBytes(a []byte) []byte
- type ExtendedTx
- type Fee
- type FeeQuote
- func (f *FeeQuote) AddQuote(ft FeeType, fee *Fee) *FeeQuote
- func (f *FeeQuote) Expired() bool
- func (f *FeeQuote) Expiry() time.Time
- func (f *FeeQuote) Fee(t FeeType) (*Fee, error)
- func (f *FeeQuote) MarshalJSON() ([]byte, error)
- func (f *FeeQuote) UnmarshalJSON(body []byte) error
- func (f *FeeQuote) UpdateExpiry(exp time.Time)
- type FeeQuotes
- func (f *FeeQuotes) AddMiner(minerName string, quote *FeeQuote) *FeeQuotes
- func (f *FeeQuotes) AddMinerWithDefault(minerName string) *FeeQuotes
- func (f *FeeQuotes) Fee(minerName string, feeType FeeType) (*Fee, error)
- func (f *FeeQuotes) Quote(minerName string) (*FeeQuote, error)
- func (f *FeeQuotes) UpdateMinerFees(minerName string, feeType FeeType, fee *Fee) (*FeeQuote, error)
- type FeeType
- type FeeUnit
- type Input
- func (i *Input) Bytes(clearLockingScript bool, intoBytes ...[]byte) []byte
- func (i *Input) ExtendedBytes(clearLockingScript bool, intoBytes ...[]byte) []byte
- func (i *Input) MarshalJSON() ([]byte, error)
- func (i *Input) PreviousTxID() []byte
- func (i *Input) PreviousTxIDAdd(txIDHash *chainhash.Hash) error
- func (i *Input) PreviousTxIDAddStr(txID string) error
- func (i *Input) PreviousTxIDChainHash() *chainhash.Hash
- func (i *Input) PreviousTxIDStr() string
- func (i *Input) ReadFrom(r io.Reader) (int64, error)
- func (i *Input) ReadFromExtended(r io.Reader) (int64, error)
- func (i *Input) String() string
- func (i *Input) UnmarshalJSON(b []byte) error
- type Output
- func (o *Output) Bytes(inBytes ...[]byte) []byte
- func (o *Output) BytesForSigHash() []byte
- func (o *Output) LockingScriptHexString() string
- func (o *Output) MarshalJSON() ([]byte, error)
- func (o *Output) NodeJSON() interface{}
- func (o *Output) ReadFrom(r io.Reader) (int64, error)
- func (o *Output) String() string
- func (o *Output) UnmarshalJSON(b []byte) error
- type Tx
- func (tx *Tx) AddHashPuzzleOutput(secret, publicKeyHash string, satoshis uint64) error
- func (tx *Tx) AddOpReturnOutput(data []byte) error
- func (tx *Tx) AddOpReturnPartsOutput(data [][]byte) error
- func (tx *Tx) AddOutput(output *Output)
- func (tx *Tx) AddP2PKHInputsFromTx(pvsTx *Tx, matchPK []byte) error
- func (tx *Tx) AddP2PKHOutputFromAddress(addr string, satoshis uint64) error
- func (tx *Tx) AddP2PKHOutputFromBip32ExtKey(privKey *bip32.ExtendedKey, satoshis uint64) (string, error)
- func (tx *Tx) AddP2PKHOutputFromPubKeyBytes(publicKeyBytes []byte, satoshis uint64) error
- func (tx *Tx) AddP2PKHOutputFromPubKeyHashStr(publicKeyHash string, satoshis uint64) error
- func (tx *Tx) AddP2PKHOutputFromPubKeyStr(publicKey string, satoshis uint64) error
- func (tx *Tx) AddP2PKHOutputFromScript(script *bscript.Script, satoshis uint64) error
- func (tx *Tx) Bytes() []byte
- func (tx *Tx) BytesWithClearedInputs(index int, lockingScript []byte) []byte
- func (tx *Tx) CalcInputPreimage(inputNumber uint32, sigHashFlag sighash.Flag) ([]byte, error)
- func (tx *Tx) CalcInputPreimageLegacy(inputNumber uint32, shf sighash.Flag) ([]byte, error)
- func (tx *Tx) CalcInputSignatureHash(inputNumber uint32, sigHashFlag sighash.Flag) ([]byte, error)
- func (tx *Tx) Change(s *bscript.Script, f *FeeQuote) error
- func (tx *Tx) ChangeToAddress(addr string, f *FeeQuote) error
- func (tx *Tx) ChangeToExistingOutput(index uint, f *FeeQuote) error
- func (tx *Tx) Clone() *Tx
- func (tx *Tx) CloneTx() *Tx
- func (tx *Tx) EstimateFeesPaid(fees *FeeQuote) (*TxFees, error)
- func (tx *Tx) EstimateIsFeePaidEnough(fees *FeeQuote) (bool, error)
- func (tx *Tx) EstimateSize() (int, error)
- func (tx *Tx) EstimateSizeWithTypes() (*TxSize, error)
- func (tx *Tx) ExtendedBytes() []byte
- func (tx *Tx) FillAllInputs(ctx context.Context, ug UnlockerGetter) error
- func (tx *Tx) FillInput(ctx context.Context, unlocker Unlocker, params UnlockerParams) error
- func (tx *Tx) From(prevTxID string, vout uint32, prevTxLockingScript string, satoshis uint64) error
- func (tx *Tx) FromUTXOs(utxos ...*UTXO) error
- func (tx *Tx) Fund(ctx context.Context, fq *FeeQuote, next UTXOGetterFunc) error
- func (tx *Tx) HasDataOutputs() bool
- func (tx *Tx) InputCount() int
- func (tx *Tx) InputIdx(i int) *Input
- func (tx *Tx) Inscribe(ia *bscript.InscriptionArgs) error
- func (tx *Tx) InscribeSpecificOrdinal(ia *bscript.InscriptionArgs, inputIdx uint32, satoshiIdx uint64, ...) error
- func (tx *Tx) InsertInputUnlockingScript(index uint32, s *bscript.Script) error
- func (tx *Tx) IsCoinbase() bool
- func (tx *Tx) IsExtended() bool
- func (tx *Tx) IsFeePaidEnough(fees *FeeQuote) (bool, error)
- func (tx *Tx) MarshalJSON() ([]byte, error)
- func (tx *Tx) NodeJSON() interface{}
- func (tx *Tx) OutputCount() int
- func (tx *Tx) OutputIdx(i int) *Output
- func (tx *Tx) OutputsHash(n int32) []byte
- func (tx *Tx) PayTo(script *bscript.Script, satoshis uint64) error
- func (tx *Tx) PayToAddress(addr string, satoshis uint64) error
- func (tx *Tx) PreviousOutHash() []byte
- func (tx *Tx) ReadFrom(r io.Reader) (int64, error)
- func (tx *Tx) SequenceHash() []byte
- func (tx *Tx) SerializeBytes() []byte
- func (tx *Tx) SetExtended(extended bool)
- func (tx *Tx) SetTxHash(hash *chainhash.Hash)
- func (tx *Tx) ShallowClone() *Tx
- func (tx *Tx) Size() int
- func (tx *Tx) SizeWithTypes() *TxSize
- func (tx *Tx) String() string
- func (tx *Tx) ToExtendedTx() *ExtendedTx
- func (tx *Tx) TotalInputSatoshis() (total uint64)
- func (tx *Tx) TotalOutputSatoshis() (total uint64)
- func (tx *Tx) TxID() string
- func (tx *Tx) TxIDBytes() []byte
- func (tx *Tx) TxIDChainHash() *chainhash.Hash
- func (tx *Tx) UnmarshalJSON(b []byte) error
- type TxFees
- type TxSize
- type Txs
- type UTXO
- type UTXOGetterFunc
- type UTXOs
- type Unlocker
- type UnlockerGetter
- type UnlockerParams
- type VarInt
Constants ΒΆ
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 )
const DefaultSequenceNumber uint32 = 0xFFFFFFFF
DefaultSequenceNumber is the default starting sequence number
const (
// DustLimit is the current minimum txo output accepted by miners.
DustLimit = 1
)
const OrdinalsPrefix = "ord"
OrdinalsPrefix contains 'ORD' the inscription protocol prefix.
Check the docs here: https://docs.1satordinals.com/
Variables ΒΆ
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") )
General errors.
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.
var ( ErrOutputNoExist = errors.New("specified output does not exist") ErrOutputTooShort = errors.New("output length too short") )
Sentinel errors reported by outputs.
var ( ErrEmptyPreviousTxID = errors.New("'PreviousTxID' not supplied") ErrEmptyPreviousTxScript = errors.New("'PreviousTxScript' not supplied") )
Sentinel errors reported by signature hash.
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 initialised, call NewFeeQuote()") ErrUnknownFeeType = errors.New("unknown fee type") )
Sentinel errors reported by the fees.
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.
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") )
Sentinel errors reported by PSBTs.
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.
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 ΒΆ
IsValidTxID will check that the txid bytes are valid.
A txid should be of 32 bytes length.
func LittleEndianBytes ΒΆ
LittleEndianBytes returns a byte array in little endian from an unsigned integer of 32 bytes.
func ReverseBytes ΒΆ
ReverseBytes reverses the bytes (little endian/big endian). This is used when computing merkle trees in Bitcoin, for example.
Types ΒΆ
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 ΒΆ
AddQuote will add a new set of quotes for a feetype or update an existing quote if it already exists.
func (*FeeQuote) Expired ΒΆ
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 ΒΆ
Expiry will return the expiry timestamp for the `bt.FeeQuote` in a threadsafe manner.
func (*FeeQuote) MarshalJSON ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
NewFeeQuotes will set up default feeQuotes for the minerName supplied, i.e., TAAL etc.
func (*FeeQuotes) AddMiner ΒΆ
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 ΒΆ
AddMinerWithDefault will add a new miner to the quotes map with default fees and immediate expiry.
func (*FeeQuotes) Fee ΒΆ
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 ΒΆ
Quote will return all fees for a miner. If no fees are found, an ErrMinerNoQuotes error is returned.
func (*FeeQuotes) UpdateMinerFees ΒΆ
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).
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) ExtendedBytes ΒΆ
ExtendedBytes encodes the Input into a hex byte array, including the EF transaction format information.
func (*Input) MarshalJSON ΒΆ
MarshalJSON will convert an input to json, expanding upon the input struct to add additional fields.
func (*Input) PreviousTxID ΒΆ
PreviousTxID will return the PreviousTxID if set.
func (*Input) PreviousTxIDAdd ΒΆ
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 ΒΆ
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 ΒΆ
PreviousTxIDChainHash returns the PreviousTxID as a chainhash.Hash.
func (*Input) PreviousTxIDStr ΒΆ
PreviousTxIDStr returns the Previous TxID as a hex string.
func (*Input) ReadFromExtended ΒΆ
ReadFromExtended reads the `io.Reader` into the `bt.Input` when the reader is consuming an extended format transaction.
func (*Input) String ΒΆ
String implements the Stringer interface and returns a string representation of a transaction input.
func (*Input) UnmarshalJSON ΒΆ
UnmarshalJSON will convert a JSON input to an input.
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 ΒΆ
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) BytesForSigHash ΒΆ
BytesForSigHash returns the proper serialization of an output to be hashed and signed (sighash).
func (*Output) LockingScriptHexString ΒΆ
LockingScriptHexString returns the locking script of an output encoded as a hex string.
func (*Output) MarshalJSON ΒΆ
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) UnmarshalJSON ΒΆ
UnmarshalJSON will convert a json serialized output to a bt Output.
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 NewTxFromBytes ΒΆ
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 ΒΆ
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 ΒΆ
NewTxFromString takes a toBytesHelper string representation of a bitcoin transaction and returns a Tx object.
func (*Tx) AddHashPuzzleOutput ΒΆ
AddHashPuzzleOutput makes an output to a hash puzzle + PKH with a value.
func (*Tx) AddOpReturnOutput ΒΆ
AddOpReturnOutput creates a new Output with OP_FALSE OP_RETURN and then the data passed in encoded as hex.
func (*Tx) AddOpReturnPartsOutput ΒΆ
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) AddP2PKHInputsFromTx ΒΆ
AddP2PKHInputsFromTx will add all Outputs of given previous transaction that match a specific public key to your transaction.
func (*Tx) AddP2PKHOutputFromAddress ΒΆ
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 ΒΆ
AddP2PKHOutputFromPubKeyBytes makes an output to a PKH with a value.
func (*Tx) AddP2PKHOutputFromPubKeyHashStr ΒΆ
AddP2PKHOutputFromPubKeyHashStr makes an output to a PKH with a value.
func (*Tx) AddP2PKHOutputFromPubKeyStr ΒΆ
AddP2PKHOutputFromPubKeyStr makes an output to a PKH with a value.
func (*Tx) AddP2PKHOutputFromScript ΒΆ
AddP2PKHOutputFromScript makes an output to a P2PKH script paid to the provided locking script with a value.
func (*Tx) Bytes ΒΆ
Bytes encodes the transaction into a byte array. See https://chainquery.com/bitcoin-cli/decoderawtransaction
func (*Tx) BytesWithClearedInputs ΒΆ
BytesWithClearedInputs encodes the transaction into a byte array but clears its Inputs first. This is used when signing transactions.
func (*Tx) CalcInputPreimage ΒΆ
CalcInputPreimage serializes the transaction based on the input index and the SIGHASH flag and returns the preimage before double hashing (SHA256d).
func (*Tx) CalcInputPreimageLegacy ΒΆ
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) CalcInputSignatureHash ΒΆ
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.
func (*Tx) Change ΒΆ
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 ΒΆ
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 ΒΆ
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) EstimateFeesPaid ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
ExtendedBytes outputs the transaction into a byte array in extended format (with PreviousTxSatoshis and PreviousTXScript included)
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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. Note, 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 ΒΆ
HasDataOutputs returns true if the transaction has at least one data (OP_RETURN) output in it.
func (*Tx) InputCount ΒΆ
InputCount returns the number of transaction Inputs.
func (*Tx) InputIdx ΒΆ
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 ΒΆ
InsertInputUnlockingScript applies a script to the transaction at a specific index in unlocking script field.
func (*Tx) IsCoinbase ΒΆ
IsCoinbase determines if this transaction is a coinbase by checking if the tx input is a standard coinbase input.
func (*Tx) IsExtended ΒΆ
IsExtended checks if the transaction is in extended format.
func (*Tx) IsFeePaidEnough ΒΆ
IsFeePaidEnough will calculate the fees that this transaction is paying including the individual fee types (std/data/etc.).
func (*Tx) MarshalJSON ΒΆ
MarshalJSON will serialize a transaction to json.
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 ΒΆ
OutputCount returns the number of transaction Inputs.
func (*Tx) OutputIdx ΒΆ
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 ΒΆ
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 ΒΆ
PayTo creates a new P2PKH output from a BitCoin address (base58) and the satoshis amount and adds that to the transaction.
func (*Tx) PayToAddress ΒΆ
PayToAddress creates a new P2PKH output from a BitCoin address (base58) and the satoshis amount and adds that to the transaction.
func (*Tx) PreviousOutHash ΒΆ
PreviousOutHash returns a byte slice of inputs outpoints, for creating a signature hash
func (*Tx) SequenceHash ΒΆ
SequenceHash returns a byte slice of inputs SequenceNumber, for creating a signature hash
func (*Tx) SerializeBytes ΒΆ added in v2.4.4
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) SetExtended ΒΆ
SetExtended sets the extended flag for the transaction.
func (*Tx) SetTxHash ΒΆ
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 ΒΆ
ShallowClone returns a clone of the tx, but only clones the elements of the tx that are mutated in the signing process.
func (*Tx) SizeWithTypes ΒΆ
SizeWithTypes will return the size of tx in bytes and include the different data types (std/data/etc.).
func (*Tx) ToExtendedTx ΒΆ
func (tx *Tx) ToExtendedTx() *ExtendedTx
ToExtendedTx converts the Tx to an ExtendedTx if it is already extended.
func (*Tx) TotalInputSatoshis ΒΆ
TotalInputSatoshis returns the total Satoshis inputted to the transaction.
func (*Tx) TotalOutputSatoshis ΒΆ
TotalOutputSatoshis returns the total Satoshis outputted from the transaction.
func (*Tx) TxID ΒΆ
TxID returns the transaction ID of the transaction (which is also the transaction hash).
func (*Tx) TxIDBytes ΒΆ added in v2.3.3
TxIDBytes returns the transaction ID of the transaction as bytes (which is also the transaction hash).
func (*Tx) TxIDChainHash ΒΆ
TxIDChainHash returns the transaction ID as a chainhash.Hash.
func (*Tx) UnmarshalJSON ΒΆ
UnmarshalJSON will unmarshal a transaction that has been marshaled with this library.
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 {}
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 ΒΆ
LockingScriptHexString return the locking script in hex format.
func (*UTXO) MarshalJSON ΒΆ
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) UnmarshalJSON ΒΆ
UnmarshalJSON will convert a JSON serialized utxo to a bt.UTXO.
type UTXOGetterFunc ΒΆ
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 ΒΆ
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
func (VarInt) Bytes ΒΆ
Bytes take the underlying unsigned integer and return a byte array in VarInt format. See http://learnmeabitcoin.com/glossary/varint
func (VarInt) Length ΒΆ
Length return the length of the underlying byte representation of the `bt.VarInt`.
func (*VarInt) ReadFrom ΒΆ
ReadFrom reads the next varint from the io.Reader and assigned it to itself.
func (VarInt) UpperLimitInc ΒΆ
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.
Source Files
ΒΆ
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 |