### Example OP_RETURN Payment Creation Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Example of creating an OP_RETURN payment to embed the string 'Hello World'. ```javascript const payment = bitcoin.payments.embed({ data: [Buffer.from('Hello World', 'utf8')] }); // Output: OP_RETURN "Hello World" ``` -------------------------------- ### Install bitcoinjs-lib and Key Management Libraries Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/README.md Install the main library and optional key management libraries like ecpair and bip32 using npm. ```bash npm install bitcoinjs-lib # Optional: install key management libraries npm install ecpair bip32 ``` -------------------------------- ### Example P2PK Payment Creation Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Example of creating a P2PK payment using a public key buffer. ```javascript const payment = bitcoin.payments.p2pk({ pubkey: pubkeyBuffer }); // Output script: 21[pubkey]ac ``` -------------------------------- ### ESM Import Example Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Demonstrates how to import bitcoinjs-lib and its components using ECMAScript Modules (ESM) syntax. ```javascript import * as bitcoin from 'bitcoinjs-lib'; import { Psbt, networks } from 'bitcoinjs-lib'; ``` -------------------------------- ### Submodule Import Example Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Shows how to import specific modules or sub-paths from the bitcoinjs-lib library, allowing for more granular control over dependencies. ```javascript // Import specific module import { payments, networks } from 'bitcoinjs-lib'; import * as address from 'bitcoinjs-lib/src/address'; import * as crypto from 'bitcoinjs-lib/src/crypto'; ``` -------------------------------- ### CJS Import Example Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Demonstrates how to import bitcoinjs-lib and its components using CommonJS (CJS) syntax, typically used in Node.js environments. ```javascript const bitcoin = require('bitcoinjs-lib'); const { Psbt, networks } = require('bitcoinjs-lib'); ``` -------------------------------- ### Example P2MS Payment Creation Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Example of creating a P2MS payment with a threshold of 2 and three public keys. ```javascript const payment = bitcoin.payments.p2ms({ m: 2, pubkeys: [pubkey1, pubkey2, pubkey3] }); ``` -------------------------------- ### Create P2WPKH Payment on Testnet Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/networks.md Example of creating a Pay-to-Witness-Public-Key-Hash payment on the testnet using a provided public key. ```javascript import { networks, payments } from 'bitcoinjs-lib'; const payment = payments.p2wpkh({ pubkey: pubkeyBuffer, network: networks.testnet }); console.log(payment.address); // tb1q... ``` -------------------------------- ### Add input and output to a transaction Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/transaction.md Example of creating a transaction and adding an input and an output. Ensure prevTxHash and scriptPubKey are correctly formatted. ```javascript import { Transaction } from 'bitcoinjs-lib'; const tx = new Transaction(); tx.addInput(prevTxHash, 0); tx.addOutput(scriptPubKey, 50000n); ``` -------------------------------- ### Access Bitcoin Network Properties Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/networks.md Example of how to access properties of the Bitcoin network configuration object. ```javascript import { networks } from 'bitcoinjs-lib'; const network = networks.bitcoin; console.log(network.bech32); // 'bc' console.log(network.bip32.public); // 0x0488b21e ``` -------------------------------- ### Access Regtest Network Properties Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/networks.md Example of how to access properties of the regtest network configuration object. ```javascript import { networks } from 'bitcoinjs-lib'; const network = networks.regtest; console.log(network.bech32); // 'bcrt' ``` -------------------------------- ### Parse and Validate a Block Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/block.md Example demonstrating how to parse a block from its hex representation, extract information, and validate its transaction roots and proof of work. ```javascript import { Block } from 'bitcoinjs-lib'; const blockHex = '01000000...'; // full block hex const block = Block.fromHex(blockHex); console.log('Block ID:', block.getId()); console.log('Timestamp:', block.getUTCDate()); console.log('Transactions:', block.transactions?.length); console.log('Has witness:', block.hasWitness()); // Validate if (!block.checkTxRoots()) { throw new Error('Merkle root mismatch'); } if (!block.checkProofOfWork()) { throw new Error('Invalid proof of work'); } console.log('Block is valid!'); ``` -------------------------------- ### Create a new PSBT instance Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md Instantiate a new PSBT object, optionally specifying network and maximum fee rate. This is the starting point for creating or modifying a PSBT. ```typescript import { Psbt, networks } from 'bitcoinjs-lib'; const psbt = new Psbt({ network: networks.bitcoin }); ``` -------------------------------- ### Block Class: From Hex and Methods Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Demonstrates creating a Block object from its hexadecimal representation and using methods to get its ID, serialize it to buffer, and validate its proof-of-work and transaction roots. ```javascript import { Block } from 'bitcoinjs-lib'; const block = Block.fromHex(hex); block.getId() // Block hash block.toBuffer() // Serialize block.checkProofOfWork() // Validate PoW block.checkTxRoots() // Validate merkle ``` -------------------------------- ### Catch Specific Address Errors Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/errors.md Catch specific errors when converting an address to an output script. This example demonstrates handling invalid addresses and wrong network prefixes. ```javascript import { address, payments } from 'bitcoinjs-lib'; try { const result = address.toOutputScript(userInput); } catch (e) { if (e instanceof Error) { if (e.message.includes('has no matching Script')) { // Handle invalid address } else if (e.message.includes('invalid prefix')) { // Handle wrong network } } } ``` -------------------------------- ### Initialize BIP32 Node with Testnet Prefixes Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/networks.md Illustrates how to create a BIP32 hierarchical deterministic node using an extended public key string and specifying the `testnet` network to ensure correct version bytes for derived keys. ```javascript import { networks } from 'bitcoinjs-lib'; import BIP32Factory from 'bip32'; // Create a BIP32 key with testnet prefixes const hdNode = BIP32Factory.fromBase58( 'tpub...', networks.testnet ); ``` -------------------------------- ### Build a P2PKH Output Script Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/script.md Constructs a Pay-to-Public-Key-Hash (P2PKH) output script using a sequence of opcodes and the public key hash. Requires importing the script module. ```javascript import { script } from 'bitcoinjs-lib'; const pubkeyHash = Buffer.from('62e907b15cbf27d5425399ebf6f0fb50ebb88f18', 'hex'); const chunks = [ script.OPS.OP_DUP, script.OPS.OP_HASH160, pubkeyHash, script.OPS.OP_EQUALVERIFY, script.OPS.OP_CHECKSIG ]; const outputScript = script.compile(chunks); ``` -------------------------------- ### Get Block Timestamp as Date Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/block.md Retrieves the block's creation timestamp and returns it as a JavaScript Date object. ```typescript getUTCDate(): Date ``` ```javascript const blockDate = block.getUTCDate(); console.log(blockDate.toUTCString()); ``` -------------------------------- ### Run Test Suite Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/README.md Execute the test suite and generate code coverage reports using npm commands. ```bash npm test npm run-script coverage ``` -------------------------------- ### Initialize Block with Custom Values Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/block.md Create a Block instance and set its properties like version and timestamp. This is useful for constructing a block manually. ```javascript import { Block } from 'bitcoinjs-lib'; const block = new Block(); block.version = 1; block.timestamp = Math.floor(Date.now() / 1000); ``` -------------------------------- ### Psbt Constructor Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md Creates a new PSBT instance. It can be initialized with optional configuration or existing PSBT data for advanced usage. ```APIDOC ## Psbt Constructor ### Description Creates a new PSBT instance. It can be initialized with optional configuration or existing PSBT data for advanced usage. ### Signature ```typescript new Psbt(opts?: PsbtOptsOptional, data?: PsbtBase) ``` ### Parameters #### Optional Parameters - **opts** (PsbtOptsOptional) - Options object, including `network` and `maximumFeeRate`. - **data** (PsbtBase) - Internal PSBT data for advanced usage. Defaults to a new `PsbtBase` instance. ### Example ```javascript import { Psbt, networks } from 'bitcoinjs-lib'; const psbt = new Psbt({ network: networks.bitcoin }); ``` ``` -------------------------------- ### Serialize Block to Hex String Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/block.md Serializes the block into a hexadecimal string representation. This method can also be used to get only the header as hex. ```typescript toHex(headersOnly?: boolean): string ``` ```javascript const hex = block.toHex(); ``` -------------------------------- ### Create P2WPKH Addresses for Different Networks Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/networks.md Demonstrates how to generate Pay-to-Witness-Public-Key-Hash (P2WPKH) addresses for Bitcoin mainnet, testnet, and regtest using the `payments.p2wpkh` function with the appropriate network object. ```javascript import { payments, networks } from 'bitcoinjs-lib'; // Mainnet P2WPKH const mainnetPayment = payments.p2wpkh({ pubkey: pubkeyBuffer, network: networks.bitcoin }); console.log(mainnetPayment.address); // bc1q... // Testnet P2WPKH const testnetPayment = payments.p2wpkh({ pubkey: pubkeyBuffer, network: networks.testnet }); console.log(testnetPayment.address); // tb1q... // Regtest P2WPKH const regtestPayment = payments.p2wpkh({ pubkey: pubkeyBuffer, network: networks.regtest }); console.log(regtestPayment.address); // bcrt1q... ``` -------------------------------- ### Calculate Transaction Virtual Size Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/transaction.md Use virtualSize() to get the transaction's virtual size in vbytes. This is useful for fee calculations. ```javascript const vsize = tx.virtualSize(); const fee = vsize * feeRate; // Calculate fee ``` -------------------------------- ### Browser Build with Browserify Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/README.md Compile bitcoinjs-lib and its dependencies into a single JavaScript file for browser use with Browserify. This allows for standalone import. ```sh npm install bitcoinjs-lib browserify npx browserify --standalone bitcoin -o bitcoinjs-lib.js <<< "module.exports = require('bitcoinjs-lib');" ``` -------------------------------- ### Extract signed transaction from PSBT Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md After finalizing all inputs, use `extractTransaction` to get the signed transaction object. You can optionally disable fee validation by setting `disableFeeCheck` to true. ```javascript psbt.finalizeAllInputs(); const tx = psbt.extractTransaction(); const txHex = tx.toHex(); ``` -------------------------------- ### Transaction Class: Construction and Methods Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Shows how to create a new Transaction object, add inputs and outputs, serialize it to hex, and calculate its virtual size. ```javascript import { Transaction } from 'bitcoinjs-lib'; const tx = new Transaction(); tx.addInput(hash, index) tx.addOutput(script, value) tx.toHex() // Serialize tx.virtualSize() // Calculate size ``` -------------------------------- ### Get Block ID (Hex String) Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/block.md Returns the block hash as a hex string, reversed for display order (big-endian), matching the format seen in block explorers. ```typescript getId(): string ``` ```javascript const blockId = block.getId(); // Returns: 'abc123...' (the hash you see in block explorers) ``` -------------------------------- ### Get Witness Commitment Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/block.md The getWitnessCommit method retrieves the 32-byte witness commitment hash from the block's coinbase output, if present. It looks for a specific OP_RETURN pattern. ```javascript const witnessCommit = block.getWitnessCommit(); if (witnessCommit) { console.log('Block has witness commitment'); } ``` -------------------------------- ### Configure PSBT Network Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/configuration.md Instantiate Psbt with specific network configurations for mainnet, testnet, or regtest. ```javascript import { Psbt, networks } from 'bitcoinjs-lib'; // Mainnet PSBT const mainnetPsbt = new Psbt({ network: networks.bitcoin }); // Testnet PSBT const testnetPsbt = new Psbt({ network: networks.testnet }); // Regtest PSBT (local testing) const regtestPsbt = new Psbt({ network: networks.regtest }); ``` -------------------------------- ### Create P2PKH Payment from Output Script Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Use this snippet to create a P2PKH payment object from a raw output script buffer. ```javascript // From script const payment3 = bitcoin.payments.p2pkh({ output: scriptBuffer }); ``` -------------------------------- ### Generate a P2WPKH Address Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/README.md Create a Pay-to-Witness-Public-Key-Hash (P2WPKH) payment object and log its address. Requires a public key buffer and network configuration. ```javascript import * as bitcoin from 'bitcoinjs-lib'; // Generate a payment const payment = bitcoin.payments.p2wpkh({ pubkey: publicKeyBuffer, network: bitcoin.networks.bitcoin }); console.log(payment.address); // bc1q... ``` -------------------------------- ### p2wpkh Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Creates a Pay-to-Witness-Public-Key-Hash (P2WPKH) payment, commonly known as SegWit v0. It features a 22-byte output script and uses witness data. ```APIDOC ## p2wpkh ### Description Creates a Pay-to-Witness-Public-Key-Hash (P2WPKH) payment, commonly known as SegWit v0. It features a 22-byte output script and uses witness data. ### Method `p2wpkh(a: Payment, opts?: PaymentOpts): Payment` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **a** (Payment) - Required - Payment object - **opts** (PaymentOpts) - Optional - Validation options ### Request Example ```javascript const payment = bitcoin.payments.p2wpkh({ pubkey: pubkeyBuffer, network: bitcoin.networks.bitcoin }); console.log(payment.address); // bc1q... ``` ### Response #### Success Response - **Payment object** #### Response Example None provided in source. ``` -------------------------------- ### Block Constructor Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/block.md Creates a new Block instance with default values for version, timestamp, bits, and nonce. Transactions and witness commitment are initially undefined. ```APIDOC ## Block Constructor Creates a new Block instance. ```typescript new Block() ``` **Default values:** - `version: 1` - `prevHash: undefined` - `merkleRoot: undefined` - `timestamp: 0` - `bits: 0` - `nonce: 0` - `transactions: undefined` - `witnessCommit: undefined` **Example:** ```javascript import { Block } from 'bitcoinjs-lib'; const block = new Block(); block.version = 1; block.timestamp = Math.floor(Date.now() / 1000); ``` ``` -------------------------------- ### Initializing ECC Library Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/configuration.md Initializes the external ECC library used for signing and key operations. Requires an implementation conforming to the TinySecp256k1Interface. ```typescript import { initEccLib } from 'bitcoinjs-lib'; import * as ecc from 'tiny-secp256k1'; initEccLib(ecc); ``` -------------------------------- ### Network Configuration Objects Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Provides predefined network configuration objects for Bitcoin mainnet, testnet, and regtest. Each configuration includes message prefix, bech32 prefix, BIP32 version bytes, and public key hash/script hash version bytes. ```javascript bitcoin.networks.bitcoin // Mainnet bitcoin.networks.testnet // Testnet bitcoin.networks.regtest // Regression test ``` -------------------------------- ### Parse and Analyze a Bitcoin Script Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/script.md Demonstrates parsing a script buffer into its constituent chunks, converting it to a human-readable ASM format, and classifying its type. ```javascript import { script } from 'bitcoinjs-lib'; const scriptBuffer = Buffer.from('76a91462e907...1888ac', 'hex'); // Decompile to chunks const chunks = script.decompile(scriptBuffer); // Convert to ASM for debugging const asm = script.toASM(scriptBuffer); console.log(asm); // "OP_DUP OP_HASH160 62e907b15cbf27d5425399ebf6f0fb50ebb88f18 OP_EQUALVERIFY OP_CHECKSIG" // Classify type const type = script.classifyOutput(scriptBuffer); console.log(type); // "p2pkh" ``` -------------------------------- ### p2wsh Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Creates a Pay-to-Witness-Script-Hash (P2WSH) payment, also SegWit v0. It uses a 34-byte output script and supports complex scripts via witness script hash. ```APIDOC ## p2wsh ### Description Creates a Pay-to-Witness-Script-Hash (P2WSH) payment, also SegWit v0. It uses a 34-byte output script and supports complex scripts via witness script hash. ### Method `p2wsh(a: Payment, opts?: PaymentOpts): Payment` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **a** (Payment) - Required - Payment object - **opts** (PaymentOpts) - Optional - Validation options ### Request Example ```javascript const innerPayment = bitcoin.payments.p2ms({ m: 2, pubkeys: [pubkey1, pubkey2, pubkey3] }); const payment = bitcoin.payments.p2wsh({ redeem: innerPayment }); console.log(payment.address); // bc1q... ``` ### Response #### Success Response - **Payment object** #### Response Example None provided in source. ``` -------------------------------- ### toXOnly Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Converts a public key to its x-only format, which is required for Taproot key-path spending. The input can be a 33 or 65-byte public key, and the output is a 32-byte x-only public key. ```APIDOC ## toXOnly ### Description Converts a public key to its x-only format, essential for Taproot key-path spending. ### Method `toXOnly(pubkey)` ### Parameters - **pubkey** (Uint8Array) - The public key buffer (33 or 65 bytes). ### Output - **xonlyKey** (Uint8Array) - The 32-byte x-only public key. ### Request Example ```javascript import { toXOnly } from 'bitcoinjs-lib'; const xonly = toXOnly(pubkeyBuffer); ``` ``` -------------------------------- ### initEccLib Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Initializes the elliptic curve cryptography library. This function must be called before any signing operations can be performed. It accepts an ECC implementation, with `tiny-secp256k1` being a common choice. ```APIDOC ## initEccLib ### Description Initializes the elliptic curve cryptography library. This is a prerequisite for signing operations. ### Method `initEccLib(eccImplementation)` ### Parameters - **eccImplementation** (object) - An ECC library implementation (e.g., `tiny-secp256k1`). ### Request Example ```javascript import { initEccLib } from 'bitcoinjs-lib'; import * as ecc from 'tiny-secp256k1'; initEccLib(ecc); ``` ### Response This function does not return a value but initializes the library for subsequent use. ``` -------------------------------- ### addInput Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md Adds a single input to the PSBT instance. Requires at least the transaction hash and output index. ```APIDOC ## addInput ### Description Adds a single input to the PSBT instance. Requires at least the transaction hash and output index. ### Signature ```typescript addInput(inputData: PsbtInputExtended): this ``` ### Parameters #### Path Parameters - **inputData** (PsbtInputExtended) - Required - An input object containing details like hash, index, and optional fields. ### Required Fields for inputData - **hash** (Uint8Array) - **index** (number) ### Optional Fields for inputData - `sequence` - `nonWitnessUtxo` - `witnessUtxo` - `redeemScript` - `witnessScript` - `tapInternalKey` - `tapMerkleRoot` - etc. ### Throws - **Error** - If required fields (`hash`, `index`) are missing. ### Returns - **this** - The PSBT instance, enabling chaining of methods. ### Example ```javascript psbt.addInput({ hash: Buffer.from('ab...', 'hex'), index: 0, sequence: 0xffffffff }); ``` ``` -------------------------------- ### addOutput Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md Adds a single output to the PSBT instance. Requires a value and either an address or a script. ```APIDOC ## addOutput ### Description Adds a single output to the PSBT instance. Requires a value and either an address or a script. ### Signature ```typescript addOutput(outputData: PsbtOutputExtended): this ``` ### Parameters #### Path Parameters - **outputData** (PsbtOutputExtended) - Required - An output object. ### Required Fields for outputData - **value** (bigint) - The output amount in satoshis. ### Required Conditions for outputData - Either `address` or `script` field must be present. ### Optional Fields for outputData - **address** (string) - The recipient's address. Will be converted to a script. - **script** (Uint8Array) - The raw script public key. ### Returns - **this** - The PSBT instance, enabling chaining of methods. ### Example ```javascript psbt.addOutput({ address: '1A1z7agoat4egoat4egoat4egoat4egoat', value: 50000n }); ``` ``` -------------------------------- ### Psbt Class: Construction and Operations Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Illustrates the creation of a Partially Signed Bitcoin Transaction (PSBT) object, adding inputs and outputs, signing inputs with a provided signer, finalizing inputs, and extracting the final transaction. ```javascript import { Psbt } from 'bitcoinjs-lib'; const psbt = new Psbt({ network: networks.bitcoin }); psbt.addInput({hash, index, witnessUtxo: {script, value}}) psbt.addOutput({address, value}) psbt.signAllInputs(signer) psbt.finalizeAllInputs() const tx = psbt.extractTransaction() ``` -------------------------------- ### Create P2WPKH Payment from Public Key Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Use this snippet to create a P2WPKH (SegWit v0) payment object from a public key. This generates a bc1q address. ```javascript const payment = bitcoin.payments.p2wpkh({ pubkey: pubkeyBuffer, network: bitcoin.networks.bitcoin }); console.log(payment.address); // bc1q... ``` -------------------------------- ### Create a new Block instance Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/block.md Instantiate a new Block object. Default values are provided for version, timestamp, bits, nonce, and other properties if not explicitly set. ```typescript new Block() ``` -------------------------------- ### getFee Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md Calculates the total transaction fee in satoshis. This method requires that all inputs have either `witnessUtxo` or `nonWitnessUtxo` defined. ```APIDOC ## getFee ### Description Calculates the transaction fee. ### Method `getFee(): bigint` ### Returns - Fee in satoshis (sum of inputs - sum of outputs) ### Note Requires all inputs to have witnessUtxo or nonWitnessUtxo ### Example ```javascript const fee = psbt.getFee(); console.log(`Fee: ${fee} satoshis`); ``` ``` -------------------------------- ### signAllInputs Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md Signs all inputs of the PSBT that match the signer's public key or public key hash. This is a convenient method for signing multiple inputs at once. ```APIDOC ## signAllInputs ### Description Signs all inputs that match the signer's pubkey/pubkeyhash. ### Method `signAllInputs(signer: Signer | SignerAsync): this` ### Parameters #### Path Parameters - **signer** (Signer | SignerAsync) - Yes - Signer to apply to matching inputs ### Response - **this** (this) - Returns `this` for chaining. ### Example ```javascript psbt.addInput({ hash: ..., index: 0, witnessUtxo: {...} }); psbt.addOutput({ address: '...', value: 40000n }); psbt.signAllInputs(signer); ``` ``` -------------------------------- ### PSBT Options Interface Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/configuration.md Defines optional configuration for the Psbt class constructor, including network and maximum fee rate. ```typescript interface PsbtOptsOptional { network?: Network; maximumFeeRate?: number; } ``` -------------------------------- ### Networks Module Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Provides configuration objects for various Bitcoin networks, including mainnet, testnet, and regtest. ```APIDOC ## Networks Module ### Network Configurations - `bitcoin.networks.bitcoin`: Mainnet configuration. - `bitcoin.networks.testnet`: Testnet configuration. - `bitcoin.networks.regtest`: Regression test configuration. Each network object exports: - `messagePrefix` (string): Message signing prefix. - `bech32` (string): Bech32 address prefix. - `bip32` (object): BIP32 key version bytes. - `pubKeyHash` (number): P2PKH version byte. - `scriptHash` (number): P2SH version byte. - `wif` (number): WIF private key version. ``` -------------------------------- ### Create P2TR Payment (Key-Path Spend) Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Use this snippet to create a P2TR (Taproot) payment for key-path spending. Provide the internal public key. ```javascript // Key-path spend const payment = bitcoin.payments.p2tr({ internalPubkey: internalPubkeyBuffer, network: bitcoin.networks.bitcoin }); console.log(payment.address); // bc1p... ``` -------------------------------- ### Transaction Constructor Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/transaction.md Creates a new Transaction instance with default values for version, locktime, inputs, and outputs. ```APIDOC ## Transaction Constructor Creates a new Transaction instance. ```typescript new Transaction() ``` **Default values:** - `version: 1` - `locktime: 0` - `ins: []` (empty inputs) - `outs: []` (empty outputs) **Example:** ```javascript import { Transaction } from 'bitcoinjs-lib'; const tx = new Transaction(); tx.addInput(prevTxHash, 0); tx.addOutput(scriptPubKey, 50000n); ``` ``` -------------------------------- ### Script Module Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Utilities for compiling and decompiling Bitcoin script chunks, converting between script formats (buffer, ASM string), and classifying script types. ```APIDOC ## Script Module ### Script Utilities - `bitcoin.script.compile(chunks)`: Compiles script chunks into a buffer. - `bitcoin.script.decompile(buffer)`: Decompiles a script buffer into chunks. - `bitcoin.script.toASM(buffer)`: Converts a script buffer to an ASM string. - `bitcoin.script.fromASM(asm)`: Converts an ASM string to a script buffer. - `bitcoin.script.isPushOnly(stack)`: Checks if a script stack contains only push operations. - `bitcoin.script.countNonPushOnlyOPs(stack)`: Counts non-push-only opcodes in a script stack. - `bitcoin.script.classifyOutput(script)`: Classifies the type of an output script. - `bitcoin.script.classifyInput(script)`: Classifies the type of an input script. ### Constants - `bitcoin.script.OPS`: Object containing Bitcoin script opcode constants. ``` -------------------------------- ### Default Transaction Properties Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/configuration.md Illustrates the default values for a new Transaction instance, including version, locktime, inputs, and outputs. ```javascript const tx = new Transaction(); // version: 1 // locktime: 0 // ins: [] // outs: [] ``` -------------------------------- ### Hierarchical Deterministic (HD) Signer Interface Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/types.md Extends the Signer interface to support BIP32 derivation paths for hierarchical deterministic key generation. Allows deriving child keys from a master key. ```typescript interface HDSigner extends Signer { derive(path: string): HDSigner; } ``` -------------------------------- ### Calculate PSBT fee Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md The `getFee` method calculates the total transaction fee in satoshis. This requires that all inputs have `witnessUtxo` or `nonWitnessUtxo` defined. ```javascript const fee = psbt.getFee(); console.log(`Fee: ${fee} satoshis`); ``` -------------------------------- ### Payments Module Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Factory functions for creating various Bitcoin payment scripts, including P2PKH, P2SH, P2WPKH, P2WSH, P2TR, P2PK, P2MS, and OP_RETURN. ```APIDOC ## Payments Module ### Payment Factories - `bitcoin.payments.p2pkh(data, opts)`: Creates a Pay-to-Public-Key-Hash payment. - `bitcoin.payments.p2sh(data, opts)`: Creates a Pay-to-Script-Hash payment. - `bitcoin.payments.p2wpkh(data, opts)`: Creates a Pay-to-Witness-PubKey-Hash payment. - `bitcoin.payments.p2wsh(data, opts)`: Creates a Pay-to-Witness-Script-Hash payment. - `bitcoin.payments.p2tr(data, opts)`: Creates a Pay-to-Taproot payment. - `bitcoin.payments.p2pk(data, opts)`: Creates a Pay-to-Public-Key payment. - `bitcoin.payments.p2ms(data, opts)`: Creates a Pay-to-Multisig payment. - `bitcoin.payments.embed(data, opts)`: Creates an OP_RETURN output for embedding data. ``` -------------------------------- ### addInputs Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md Adds multiple inputs to the PSBT instance, allowing for batch addition of transaction inputs. ```APIDOC ## addInputs ### Description Adds multiple inputs to the PSBT instance, allowing for batch addition of transaction inputs. ### Signature ```typescript addInputs(inputDatas: PsbtInputExtended[]): this ``` ### Parameters #### Path Parameters - **inputDatas** (PsbtInputExtended[]) - Required - An array of input objects to be added. ### Returns - **this** - The PSBT instance, enabling chaining of methods. ### Example ```javascript psbt.addInputs([ { hash: prevTxHash1, index: 0 }, { hash: prevTxHash2, index: 1 } ]); ``` ``` -------------------------------- ### Create P2PKH Payment from Address Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Use this snippet to create a P2PKH payment object directly from a Bitcoin address. ```javascript // From address const payment2 = bitcoin.payments.p2pkh({ address: '1A1z7agoat4egoat4egoat4egoat4egoat4egoat' }); ``` -------------------------------- ### Setting Maximum Fee Rate After Construction Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/configuration.md Allows setting the maximum fee rate for a PSBT after it has been constructed using the setMaximumFeeRate method. This provides flexibility in configuring fee limits. ```javascript import { Psbt } from 'bitcoinjs-lib'; const psbt2 = new Psbt({ maximumFeeRate: 10000 }); // Option 2: Set after construction psbt.setMaximumFeeRate(10000); ``` -------------------------------- ### Create P2PKH Payment from Public Key Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Use this snippet to create a P2PKH payment object from a public key. Ensure you provide the network object. ```javascript import * as bitcoin from 'bitcoinjs-lib'; // From public key const payment = bitcoin.payments.p2pkh({ pubkey: pubkeyBuffer, network: bitcoin.networks.bitcoin }); console.log(payment.address); // 1A1z7agoat... ``` -------------------------------- ### fromOutputScript Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/address.md Converts a transaction output script to a human-readable Bitcoin address. It supports various address types including P2PKH, P2SH, P2WPKH, P2WSH, and P2TR. ```APIDOC ## fromOutputScript ### Description Converts a transaction output script to a human-readable Bitcoin address. It supports various address types including P2PKH, P2SH, P2WPKH, P2WSH, and P2TR. ### Method ```typescript function fromOutputScript(output: Uint8Array, network?: Network): string ``` ### Parameters #### Path Parameters - **output** (Uint8Array) - Required - The output script buffer - **network** (Network) - Optional - Network object specifying address format (defaults to bitcoin) ### Returns Human-readable Bitcoin address string ### Throws `Error` if the output script does not match any known address type (P2PKH, P2SH, P2WPKH, P2WSH, P2TR, future segwit) ### Example ```javascript import * as bitcoin from 'bitcoinjs-lib'; const output = Buffer.from('76a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac', 'hex'); const address = bitcoin.address.fromOutputScript(output); // Returns: 1A1z7agoat4egoat4egoat4egoat4egoat ``` ``` -------------------------------- ### Top-Level Exports Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Exports all public modules, key types, and utility functions directly from the main bitcoinjs-lib entry point. ```APIDOC ## Top-Level Exports ### Modules - `bitcoin.address`: Address encoding/decoding - `bitcoin.crypto`: Cryptographic functions - `bitcoin.networks`: Network configurations - `bitcoin.payments`: Payment factories - `bitcoin.script`: Script utilities ### Classes - `bitcoin.Block`: Block representation - `bitcoin.Transaction`: Transaction representation - `bitcoin.Psbt`: Partially Signed Bitcoin Transaction ### Types - `bitcoin.Network` - `bitcoin.Payment` - `bitcoin.Signer` - `bitcoin.SignerAsync` - `bitcoin.HDSigner` - `bitcoin.HDSignerAsync` - `bitcoin.Tapleaf` - `bitcoin.Taptree` ### Functions - `bitcoin.initEccLib(ecc)`: Initialize ECC library - `bitcoin.toXOnly(pubkey)`: Convert to x-only format ``` -------------------------------- ### Create Custom Network Configuration Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/configuration.md Define a custom network object with specific parameters for Bitcoin-like blockchains. This is typically used for local development or private networks. ```javascript const customNetwork = { messagePrefix: '\x18Custom Network:\n', bech32: 'custom', bip32: { public: 0x0488b21e, private: 0x0488ade4, }, pubKeyHash: 0x00, scriptHash: 0x05, wif: 0x80, }; const payment = payments.p2wpkh({ pubkey: pubkeyBuffer, network: customNetwork }); ``` -------------------------------- ### Create a new Transaction instance Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/transaction.md Instantiate a new Transaction object. Default values for version, locktime, inputs, and outputs are used. ```typescript new Transaction() ``` -------------------------------- ### Convert Public Key to X-Only Format Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Converts a public key (33 or 65 bytes) to its 32-byte x-only format, which is required for Taproot key-path spending. ```typescript import { toXOnly } from 'bitcoinjs-lib'; const xonly = toXOnly(pubkeyBuffer); // 32-byte x-only key ``` -------------------------------- ### addOutputs Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md Adds multiple outputs to the PSBT instance, allowing for batch addition of transaction outputs. ```APIDOC ## addOutputs ### Description Adds multiple outputs to the PSBT instance, allowing for batch addition of transaction outputs. ### Signature ```typescript addOutputs(outputDatas: PsbtOutputExtended[]): this ``` ### Parameters #### Path Parameters - **outputDatas** (PsbtOutputExtended[]) - Required - An array of output objects to be added. ### Returns - **this** - The PSBT instance, enabling chaining of methods. ### Example ```javascript psbt.addOutputs([ { address: 'bc1q...', value: 50000n }, { address: 'bc1q...', value: 30000n } ]); ``` ``` -------------------------------- ### Create P2TR Payment (Script-Path Spend) Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Use this snippet to create a P2TR (Taproot) payment for script-path spending, including a script tree. ```javascript // Script-path spend with script tree const leafScript = bitcoin.script.compile([...]); const scriptTree = { output: leafScript }; const payment2 = bitcoin.payments.p2tr({ internalPubkey: internalPubkeyBuffer, scriptTree: scriptTree }); ``` -------------------------------- ### p2pkh Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Creates a Pay-to-Public-Key-Hash (P2PKH) payment. It can be constructed from a public key, address, or script output. ```APIDOC ## p2pkh ### Description Creates a Pay-to-Public-Key-Hash (P2PKH) payment. It can be constructed from a public key, address, or script output. ### Method `p2pkh(a: Payment, opts?: PaymentOpts): Payment` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **a** (Payment) - Required - Payment object (see Payment interface) - **opts** (PaymentOpts) - Optional - Validation options ### Request Example ```javascript import * as bitcoin from 'bitcoinjs-lib'; // From public key const payment = bitcoin.payments.p2pkh({ pubkey: pubkeyBuffer, network: bitcoin.networks.bitcoin }); console.log(payment.address); // 1A1z7agoat... // From address const payment2 = bitcoin.payments.p2pkh({ address: '1A1z7agoat4egoat4egoat4egoat4egoat' }); // From script const payment3 = bitcoin.payments.p2pkh({ output: scriptBuffer }); ``` ### Response #### Success Response - **Payment object** with address, output script, hash, etc. #### Response Example None provided in source. ``` -------------------------------- ### Convert Output Script to Address Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/address.md Use `fromOutputScript` to convert a transaction output script into a human-readable Bitcoin address. It supports various address types including P2PKH, P2SH, P2WPKH, P2WSH, and P2TR. An optional network parameter can specify the address format. ```javascript import * as bitcoin from 'bitcoinjs-lib'; const output = Buffer.from('76a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac', 'hex'); const address = bitcoin.address.fromOutputScript(output); // Returns: 1A1z7agoat4egoat4egoat4egoat4egoat ``` -------------------------------- ### Script Module Utilities Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Provides utilities for compiling and decompiling script chunks, converting between script buffers and ASM strings, checking for push-only operations, and classifying script types. ```javascript bitcoin.script.compile(chunks) // Chunks → buffer bitcoin.script.decompile(buffer) // Buffer → chunks bitcoin.script.toASM(buffer) // Buffer → ASM string bitcoin.script.fromASM(asm) // ASM string → buffer bitcoin.script.isPushOnly(stack) // Check if push-only bitcoin.script.countNonPushOnlyOPs(stack) // Count opcodes bitcoin.script.OPS // Opcode constants bitcoin.script.classifyOutput(script) // Classify output type bitcoin.script.classifyInput(script) // Classify input type ``` -------------------------------- ### fromBech32 Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/address.md Converts a Bech32 or Bech32m encoded address to its version, prefix, and data. This is used for modern SegWit addresses. ```APIDOC ## fromBech32 ### Description Converts a Bech32 or Bech32m encoded address to its version, prefix, and data. This is used for modern SegWit addresses. ### Method ```typescript function fromBech32(address: string): Bech32Result ``` ### Parameters #### Path Parameters - **address** (string) - Required - The Bech32 or Bech32m encoded address ### Returns `Bech32Result` with `version: number`, `prefix: string`, `data: Uint8Array` ### Throws `TypeError` if the address uses the wrong encoding (e.g., bech32 for v1 pubkey) ### Example ```javascript const result = bitcoin.address.fromBech32('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4'); console.log(result.version); // 0 for P2WPKH/P2WSH console.log(result.prefix); // 'bc' for Bitcoin mainnet console.log(result.data); // 20 or 32 bytes ``` ``` -------------------------------- ### Address Module Functions Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Provides functions for parsing and encoding Bitcoin addresses using Base58Check and Bech32 formats. Also includes utilities for converting between addresses and output scripts. ```javascript import * as bitcoin from 'bitcoinjs-lib'; bitcoin.address.fromBase58Check(address) // Parse base58check bitcoin.address.fromBech32(address) // Parse bech32 bitcoin.address.toBase58Check(hash, version) // Encode base58check bitcoin.address.toBech32(data, version, prefix) // Encode bech32 bitcoin.address.fromOutputScript(script, network) // Script → address bitcoin.address.toOutputScript(address, network) // Address → script ``` -------------------------------- ### Create P2PK Payment Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/payments.md Use this function to create a Pay-to-Public-Key (P2PK) payment object. Requires a public key. ```typescript function p2pk(a: Payment, opts?: PaymentOpts): Payment ``` -------------------------------- ### Sign all matching PSBT inputs Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/psbt.md Use `signAllInputs` to sign all inputs in a PSBT that match the provided signer's public key or public key hash. This is convenient for signing all inputs belonging to a specific key. ```javascript psbt.addInput({ hash: ..., index: 0, witnessUtxo: {...} }); psbt.addOutput({ address: '...', value: 40000n }); psbt.signAllInputs(signer); ``` -------------------------------- ### toOutputScript Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/address.md Converts a human-readable Bitcoin address to its corresponding output script in the form of a Uint8Array. It can optionally validate against a specific network. ```APIDOC ## toOutputScript ### Description Converts a human-readable Bitcoin address to its corresponding output script. This function is useful for generating the script that can be used in a transaction output. ### Method ```typescript function toOutputScript(address: string, network?: Network): Uint8Array ``` ### Parameters #### Path Parameters - **address** (string) - Yes - Human-readable Bitcoin address - **network** (Network) - No - Network object to validate prefix (defaults to 'bitcoin') ### Response #### Success Response - **Uint8Array**: Containing the output script bytes. ### Throws - **Error**: If the address has an invalid prefix or no matching script. ### Example ```javascript const address = '1A1z7agoat4egoat4egoat4egoat4egoat'; const output = bitcoin.address.toOutputScript(address); // Returns: Uint8Array of script bytes ``` ``` -------------------------------- ### Crypto Module Functions Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/index.md Offers core cryptographic hashing functions including HASH160, SHA256, SHA1, RIPEMD160, and BIP-340 tagged hashes. Also provides access to prefix constants for tagged hashing. ```javascript bitcoin.crypto.hash160(buffer) // HASH160 bitcoin.crypto.hash256(buffer) // SHA256(SHA256) bitcoin.crypto.sha256(buffer) // SHA256 bitcoin.crypto.sha1(buffer) // SHA1 bitcoin.crypto.ripemd160(buffer) // RIPEMD160 bitcoin.crypto.taggedHash(prefix, data) // BIP-340 tagged hash bitcoin.crypto.TAGGED_HASH_PREFIXES // Object of prefix constants ``` -------------------------------- ### Compute Hash for Taproot (v1 Witness) Signature Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/transaction.md Use hashForWitnessV1() for signing Taproot inputs according to BIP-341. It requires input index, all previous output scripts and values, and the hash type. Optional leafHash and annex can be provided. ```typescript hashForWitnessV1( inIndex: number, prevOutScripts: Uint8Array[], values: bigint[], hashType: number, leafHash?: Uint8Array, annex?: Uint8Array ): Uint8Array ``` -------------------------------- ### Setting Maximum Fee Rate in PSBT Constructor Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/configuration.md Configures the maximum fee rate allowed for a PSBT by passing the 'maximumFeeRate' option to the Psbt constructor. This limits the fee per byte (in satoshis). ```javascript import { Psbt } from 'bitcoinjs-lib'; const psbt = new Psbt({ maximumFeeRate: 5000 }); ``` -------------------------------- ### fromASM Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/api-reference/script.md Converts an ASM notation string into a compiled script buffer (Uint8Array). This allows for creating scripts from a human-readable format. ```APIDOC ## fromASM ### Description Converts ASM notation to a script buffer. ### Method `fromASM` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **asm** (string) - Required - ASM notation string ### Request Example ```javascript const asm = "OP_DUP OP_HASH160 62e907b15cbf27d5425399ebf6f0fb50ebb88f18 OP_EQUALVERIFY OP_CHECKSIG"; const script = script.fromASM(asm); ``` ### Response #### Success Response * **Compiled script buffer** (Uint8Array) #### Response Example None provided. ``` -------------------------------- ### Default Block Properties Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/configuration.md Shows the default values for a new Block instance, including version, timestamps, and other block-specific fields. ```javascript const block = new Block(); // version: 1 // prevHash: undefined // merkleRoot: undefined // timestamp: 0 // bits: 0 // nonce: 0 // transactions: undefined // witnessCommit: undefined ``` -------------------------------- ### Configure Payment Validation Source: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/_autodocs/configuration.md Instantiate payment objects with or without runtime validation. Disabling validation can improve performance but is less safe. ```javascript import { payments } from 'bitcoinjs-lib'; // With validation (default) const payment = payments.p2wpkh({ pubkey: pubkeyBuffer, network: networks.bitcoin }); // Skip validation (unsafe) const payment2 = payments.p2wpkh( { pubkey: pubkeyBuffer }, { validate: false } ); ```