UNPKG

@bsv/sdk

Version:

BSV Blockchain Software Development Kit

292 lines 14 kB
import TransactionInput from './TransactionInput.js'; import TransactionOutput from './TransactionOutput.js'; import { Reader } from '../primitives/utils.js'; import FeeModel from './FeeModel.js'; import { Broadcaster, BroadcastResponse, BroadcastFailure } from './Broadcaster.js'; import MerklePath from './MerklePath.js'; import ChainTracker from './ChainTracker.js'; /** * Represents a complete Bitcoin transaction. This class encapsulates all the details * required for creating, signing, and processing a Bitcoin transaction, including * inputs, outputs, and various transaction-related methods. * * @class Transaction * @property {number} version - The version number of the transaction. Used to specify * which set of rules this transaction follows. * @property {TransactionInput[]} inputs - An array of TransactionInput objects, representing * the inputs for the transaction. Each input references a previous transaction's output. * @property {TransactionOutput[]} outputs - An array of TransactionOutput objects, representing * the outputs for the transaction. Each output specifies the amount of satoshis to be * transferred and the conditions under which they can be spent. * @property {number} lockTime - The lock time of the transaction. If non-zero, it specifies the * earliest time or block height at which the transaction can be added to the block chain. * @property {Record<string, any>} metadata - A key-value store for attaching additional data to * the transaction object, not included in the transaction itself. Useful for adding descriptions, internal reference numbers, or other information. * @property {MerkleProof} [merklePath] - Optional. A merkle proof demonstrating the transaction's * inclusion in a block. Useful for transaction verification using SPV. * * @example * // Creating a new transaction * let tx = new Transaction(); * tx.addInput(...); * tx.addOutput(...); * await tx.fee(); * await tx.sign(); * await tx.broadcast(); * * @description * The Transaction class provides comprehensive * functionality to handle various aspects of transaction creation, including * adding inputs and outputs, computing fees, signing the transaction, and * generating its binary or hexadecimal representation. */ export default class Transaction { version: number; inputs: TransactionInput[]; outputs: TransactionOutput[]; lockTime: number; metadata: Record<string, any>; merklePath?: MerklePath; private cachedHash?; private static addPathOrInputs; /** * Creates a new transaction, linked to its inputs and their associated merkle paths, from a BEEF V1, V2 or Atomic. * Optionally, you can provide a specific TXID to retrieve a particular transaction from the BEEF data. * If the TXID is provided but not found in the BEEF data, an error will be thrown. * If no TXID is provided, the last transaction in the BEEF data is returned, or the atomic txid. * @param beef A binary representation of transactions in BEEF format. * @param txid Optional TXID of the transaction to retrieve from the BEEF data. * @returns An anchored transaction, linked to its associated inputs populated with merkle paths. */ static fromBEEF(beef: number[], txid?: string): Transaction; /** * Creates a new transaction from an Atomic BEEF (BRC-95) structure. * Extracts the subject transaction and supporting merkle path and source transactions contained in the BEEF data * * @param beef A binary representation of an Atomic BEEF structure. * @returns The subject transaction, linked to its associated inputs populated with merkle paths. */ static fromAtomicBEEF(beef: number[]): Transaction; private static fromAnyBeef; /** * Creates a new transaction, linked to its inputs and their associated merkle paths, from a EF (BRC-30) structure. * @param ef A binary representation of a transaction in EF format. * @returns An extended transaction, linked to its associated inputs by locking script and satoshis amounts only. */ static fromEF(ef: number[]): Transaction; /** * Since the validation of blockchain data is atomically transaction data validation, * any application seeking to validate data in output scripts must store the entire transaction as well. * Since the transaction data includes the output script data, saving a second copy of potentially * large scripts can bloat application storage requirements. * * This function efficiently parses binary transaction data to determine the offsets and lengths of each script. * This supports the efficient retreival of script data from transaction data. * * @param bin binary transaction data * @returns { * inputs: { vin: number, offset: number, length: number }[] * outputs: { vout: number, offset: number, length: number }[] * } */ static parseScriptOffsets(bin: number[]): { inputs: Array<{ vin: number; offset: number; length: number; }>; outputs: Array<{ vout: number; offset: number; length: number; }>; }; static fromReader(br: Reader): Transaction; /** * Creates a Transaction instance from a binary array. * * @static * @param {number[]} bin - The binary array representation of the transaction. * @returns {Transaction} - A new Transaction instance. */ static fromBinary(bin: number[]): Transaction; /** * Creates a Transaction instance from a hexadecimal string. * * @static * @param {string} hex - The hexadecimal string representation of the transaction. * @returns {Transaction} - A new Transaction instance. */ static fromHex(hex: string): Transaction; /** * Creates a Transaction instance from a hexadecimal string encoded EF. * * @static * @param {string} hex - The hexadecimal string representation of the transaction EF. * @returns {Transaction} - A new Transaction instance. */ static fromHexEF(hex: string): Transaction; /** * Creates a Transaction instance from a hexadecimal string encoded BEEF. * Optionally, you can provide a specific TXID to retrieve a particular transaction from the BEEF data. * If the TXID is provided but not found in the BEEF data, an error will be thrown. * If no TXID is provided, the last transaction in the BEEF data is returned. * * @static * @param {string} hex - The hexadecimal string representation of the transaction BEEF. * @param {string} [txid] - Optional TXID of the transaction to retrieve from the BEEF data. * @returns {Transaction} - A new Transaction instance. */ static fromHexBEEF(hex: string, txid?: string): Transaction; constructor(version?: number, inputs?: TransactionInput[], outputs?: TransactionOutput[], lockTime?: number, metadata?: Record<string, any>, merklePath?: MerklePath); /** * Adds a new input to the transaction. * * @param {TransactionInput} input - The TransactionInput object to add to the transaction. * @throws {Error} - If the input does not have a sourceTXID or sourceTransaction defined. */ addInput(input: TransactionInput): void; /** * Adds a new output to the transaction. * * @param {TransactionOutput} output - The TransactionOutput object to add to the transaction. */ addOutput(output: TransactionOutput): void; /** * Adds a new P2PKH output to the transaction. * * @param {number[] | string} address - The P2PKH address of the output. * @param {number} [satoshis] - The number of satoshis to send to the address - if not provided, the output is considered a change output. * */ addP2PKHOutput(address: number[] | string, satoshis?: number): void; /** * Updates the transaction's metadata. * * @param {Record<string, any>} metadata - The metadata object to merge into the existing metadata. */ updateMetadata(metadata: Record<string, any>): void; /** * Computes fees prior to signing. * If no fee model is provided, uses a SatoshisPerKilobyte fee model that pays 1 sat/kb. * If fee is a number, the transaction uses that value as fee. * * @param modelOrFee - The initialized fee model to use or fixed fee for the transaction * @param changeDistribution - Specifies how the change should be distributed * amongst the change outputs * */ fee(modelOrFee?: FeeModel | number, changeDistribution?: 'equal' | 'random'): Promise<void>; private calculateChange; private distributeChange; private distributeRandomChange; private distributeEqualChange; private benfordNumber; /** * Utility method that returns the current fee based on inputs and outputs * * @returns The current transaction fee */ getFee(): number; /** * Signs a transaction, hydrating all its unlocking scripts based on the provided script templates where they are available. */ sign(): Promise<void>; /** * Broadcasts a transaction. * * @param broadcaster The Broadcaster instance wwhere the transaction will be sent * @returns A BroadcastResponse or BroadcastFailure from the Broadcaster */ broadcast(broadcaster?: Broadcaster): Promise<BroadcastResponse | BroadcastFailure>; /** * Converts the transaction to a binary array format. * * @returns {number[]} - The binary array representation of the transaction. */ toBinary(): number[]; /** * Converts the transaction to a BRC-30 EF format. * * @returns {number[]} - The BRC-30 EF representation of the transaction. */ toEF(): number[]; /** * Converts the transaction to a hexadecimal string EF. * * @returns {string} - The hexadecimal string representation of the transaction EF. */ toHexEF(): string; /** * Converts the transaction to a hexadecimal string format. * * @returns {string} - The hexadecimal string representation of the transaction. */ toHex(): string; /** * Converts the transaction to a hexadecimal string BEEF. * * @returns {string} - The hexadecimal string representation of the transaction BEEF. */ toHexBEEF(): string; /** * Converts the transaction to a hexadecimal string Atomic BEEF. * * @returns {string} - The hexadecimal string representation of the transaction Atomic BEEF. */ toHexAtomicBEEF(): string; /** * Calculates the transaction's hash. * * @param {'hex' | undefined} enc - The encoding to use for the hash. If 'hex', returns a hexadecimal string; otherwise returns a binary array. * @returns {string | number[]} - The hash of the transaction in the specified format. */ hash(enc?: 'hex'): number[] | string; /** * Calculates the transaction's ID in binary array. * * @returns {number[]} - The ID of the transaction in the binary array format. */ id(): number[]; /** * Calculates the transaction's ID in hexadecimal format. * * @param {'hex'} enc - The encoding to use for the ID. If 'hex', returns a hexadecimal string. * @returns {string} - The ID of the transaction in the hex format. */ id(enc: 'hex'): string; /** * Verifies the legitimacy of the Bitcoin transaction according to the rules of SPV by ensuring all the input transactions link back to valid block headers, the chain of spends for all inputs are valid, and the sum of inputs is not less than the sum of outputs. * * @param chainTracker - An instance of ChainTracker, a Bitcoin block header tracker. If the value is set to 'scripts only', headers will not be verified. If not provided then the default chain tracker will be used. * @param feeModel - An instance of FeeModel, a fee model to use for fee calculation. If not provided then the default fee model will be used. * @param memoryLimit - The maximum memory in bytes usage allowed for script evaluation. If not provided then the default memory limit will be used. * * @returns Whether the transaction is valid according to the rules of SPV. * * @example tx.verify(new WhatsOnChain(), new SatoshisPerKilobyte(1)) */ verify(chainTracker?: ChainTracker | 'scripts only', feeModel?: FeeModel, memoryLimit?: number): Promise<boolean>; /** * Serializes this transaction, together with its inputs and the respective merkle proofs, into the BEEF (BRC-62) format. This enables efficient verification of its compliance with the rules of SPV. * * @param allowPartial If true, error will not be thrown if there are any missing sourceTransactions. * * @returns The serialized BEEF structure * @throws Error if there are any missing sourceTransactions unless `allowPartial` is true. */ toBEEF(allowPartial?: boolean): number[]; /** * Serializes this transaction and its inputs into the Atomic BEEF (BRC-95) format. * The Atomic BEEF format starts with a 4-byte prefix `0x01010101`, followed by the TXID of the subject transaction, * and then the BEEF data containing only the subject transaction and its dependencies. * This format ensures that the BEEF structure is atomic and contains no unrelated transactions. * * @param allowPartial If true, error will not be thrown if there are any missing sourceTransactions. * * @returns {number[]} - The serialized Atomic BEEF structure. * @throws Error if there are any missing sourceTransactions unless `allowPartial` is true. */ toAtomicBEEF(allowPartial?: boolean): number[]; } //# sourceMappingURL=Transaction.d.ts.map