Documentation ¶
Overview ¶
Package bt provides functions needed to create and manipulate Bitcoin transactions.
Index ¶
- Constants
- Variables
- func DecodeVarInt(b []byte) (result uint64, size int)
- func IsValidTxID(txid []byte) bool
- func LittleEndianBytes(v uint32, l uint32) []byte
- func ReverseBytes(a []byte) []byte
- func VarInt(i uint64) []byte
- func VarIntUpperLimitInc(length uint64) int
- type Fee
- type FeeQuote
- 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(clear bool) []byte
- func (i *Input) MarshalJSON() ([]byte, error)
- func (i *Input) PreviousTxID() []byte
- func (i *Input) PreviousTxIDAdd(txID []byte) error
- func (i *Input) PreviousTxIDAddStr(txID string) error
- func (i *Input) PreviousTxIDStr() string
- func (i *Input) String() string
- func (i *Input) UnmarshalJSON(b []byte) error
- type LocalUnlocker
- type LocalUnlockerGetter
- type Output
- 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) ApplyP2PKHUnlockingScript(index uint32, pubKey []byte, sig []byte, shf sighash.Flag) error
- func (tx *Tx) ApplyUnlockingScript(index uint32, s *bscript.Script) 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) 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) 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) IsCoinbase() 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) SequenceHash() []byte
- func (tx *Tx) Size() int
- func (tx *Tx) SizeWithTypes() *TxSize
- func (tx *Tx) String() string
- 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) Unlock(ctx context.Context, u Unlocker, idx uint32, shf sighash.Flag) error
- func (tx *Tx) UnlockAll(ctx context.Context, ug UnlockerGetter) error
- func (tx *Tx) UnmarshalJSON(b []byte) error
- type TxFees
- type TxSize
- type Txs
- type UTXO
- type UTXOGetterFunc
- type UTXOs
- type Unlocker
- type UnlockerGetter
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 = 136
)
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") )
General errors.
var ( ErrInputNoExist = errors.New("specified input does not exist") ErrInputTooShort = errors.New("input length too short") )
Sentinal errors reported by inputs.
var ( ErrOutputNoExist = errors.New("specified output does not exist") ErrOutputTooShort = errors.New("output length too short") )
Sentinal errors reported by outputs.
var ( ErrEmptyPreviousTxID = errors.New("'PreviousTxID' not supplied") ErrEmptyPreviousTxScript = errors.New("'PreviousTxScript' not supplied") )
Sentinal 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 Fund
var (
ErrInsufficientInputs = errors.New("satoshis inputted to the tx are less than the outputted satoshis")
)
Sentinal errors reported by change.
Functions ¶
func DecodeVarInt ¶
DecodeVarInt takes a byte array in VarInt format and returns the decoded unsigned integer value of the length, and it's size in bytes. See http://learnmeabitcoin.com/glossary/varint
func IsValidTxID ¶
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.
func VarInt ¶
VarInt takes an unsigned integer and returns a byte array in VarInt format. See http://learnmeabitcoin.com/glossary/varint
func VarIntUpperLimitInc ¶
VarIntUpperLimitInc returns true if a number is at the upper limit of a VarInt and will result in a VarInt length change if incremented. The value returned will indicate how many bytes will be increase if the length in incremented. -1 will be returned when the upper limit of VarInt is reached.
Types ¶
type Fee ¶
type Fee struct { FeeType 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 an 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 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) 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, ie TAAL etc.
func (*FeeQuotes) AddMiner ¶
AddMiner will add a new miner to the quotes 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 & 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 (eg: 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 - Optimised for memory via maligned
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) PreviousTxIDStr ¶
PreviousTxIDStr returns the Previous TxID as a hex string.
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 LocalUnlocker ¶
type LocalUnlocker struct {
PrivateKey *bec.PrivateKey
}
LocalUnlocker implements the unlocker interface. It is used to unlock a tx locally using a bec Private Key.
func (*LocalUnlocker) Unlock ¶
Unlock a transaction at a given input using the PrivateKey passed in through the LocalUnlocker struct. Unlock generates, applies, and returns an ECDSA signature for the provided hash digest using the private key as well as the public key corresponding to the private key used. The produced signature is deterministic (same message and same key yield the same signature) and canonical in accordance with RFC6979 and BIP0062.
type LocalUnlockerGetter ¶
type LocalUnlockerGetter struct {
PrivateKey *bec.PrivateKey
}
LocalUnlockerGetter implements the UnlockerGetter interface. It unlocks a Tx locally, using a bec PrivateKey.
type Output ¶
Output is a representation of a transaction output
func (*Output) BytesForSigHash ¶
BytesForSigHash returns the proper serialisation 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 serialise an output to json.
func (*Output) NodeJSON ¶
func (o *Output) NodeJSON() interface{}
NodeJSON returns a wrapped *bt.Output for marshalling/unmarshalling into a node output format.
Marshalling 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 serialised output to a bt Output.
type Tx ¶
Tx wraps a bitcoin transaction
DO NOT CHANGE ORDER - Optimised 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 actually 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) ApplyP2PKHUnlockingScript ¶
func (tx *Tx) ApplyP2PKHUnlockingScript(index uint32, pubKey []byte, sig []byte, shf sighash.Flag) error
ApplyP2PKHUnlockingScript applies a script to the transaction at a specific index in unlocking script field.
func (*Tx) ApplyUnlockingScript ¶
ApplyUnlockingScript applies a script to the transaction at a specific index in unlocking script field.
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 serialises the transaction based on the input index and the SIGHASH flag and returns the preimage before double hashing (SHA256d).
func (*Tx) CalcInputPreimageLegacy ¶
CalcInputPreimageLegacy serialises 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 serialised the transaction and returns the hash digest to be signed. BitCoin (SV) uses a different signature hashing algorithm after the UAHF fork for replay protection.
func (*Tx) Change ¶
Change calculates the amount 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 amount 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 finalised 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) From ¶
From adds a new input to the transaction from the specified UTXO fields, using the default finalised sequence number (0xFFFFFFFF). If you want a different nSeq, change it manually afterwards.
func (*Tx) FromUTXOs ¶
FromUTXOs adds a new input to the transaction from the specified *bt.UTXO fields, using the default finalised sequence number (0xFFFFFFFF). If you want a different nSeq, change it manually afterwards.
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) IsCoinbase ¶
IsCoinbase determines if this transaction is a coinbase by checking if the tx input is a standard coinbase input.
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 serialise a transaction to json.
func (*Tx) NodeJSON ¶
func (tx *Tx) NodeJSON() interface{}
NodeJSON returns a wrapped *bt.Tx for marshalling/unmarshalling into a node tx format.
Marshalling 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) SizeWithTypes ¶
SizeWithTypes will return the size of tx in bytes and include the different data types (std/data/etc.).
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 ¶
TxIDBytes returns the transaction ID of the transaction as bytes (which is also the transaction hash).
func (*Tx) Unlock ¶
Unlock 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/nonsignature based.
func (*Tx) UnlockAll ¶
func (tx *Tx) UnlockAll(ctx context.Context, ug UnlockerGetter) error
UnlockAll 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.
func (*Tx) UnmarshalJSON ¶
UnmarshalJSON will unmarshall a transaction that has been marshalled with this library.
type TxFees ¶
type TxFees struct { // TotalFeePaid is the total amount 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 amount of bytes for the entire tx. TotalBytes uint64 // TotalStdBytes are the amount 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 marshalling/unmarshalling into a node tx format.
Marshalling 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 { TxID []byte Vout uint32 LockingScript *bscript.Script Satoshis uint64 SequenceNumber uint32 }
UTXO an unspent transaction output, used for creating inputs
func (*UTXO) LockingScriptHexString ¶
LockingScriptHexString retur nthe locking script in hex format.
func (*UTXO) MarshalJSON ¶
MarshalJSON will serialise a utxo to json.
func (*UTXO) NodeJSON ¶
func (u *UTXO) NodeJSON() interface{}
NodeJSON returns a wrapped *bt.UTXO for marshalling/unmarshalling into a node utxo format.
Marshalling 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 serialised 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 marshalling/unmarshalling into a node utxo format.
Marshalling usage example:
bb, err := json.Marshal(utxos.NodeJSON())
Unmarshalling usage example:
var txs bt.UTXOs if err := json.Unmarshal(bb, utxos.NodeJSON()); err != nil {}
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
interpreter
Package interpreter implements the bitcoin transaction script language.
|
Package interpreter implements the bitcoin transaction script language. |
examples
|
|