### Example: Signing a Bitcoin Message Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/BitcoinMessage.md Demonstrates how to sign a message for different address types (P2PKH, P2SH-P2WPKH, P2WPKH) and with additional entropy. ```typescript import { BitcoinMessage } from 'bip322-js'; const message = 'Hello World'; const privateKey = Buffer.from('abcdef0123456789...', 'hex'); // 32 bytes // Sign for P2PKH address const p2pkhSig = BitcoinMessage.sign(message, privateKey, true); // compressed=true console.log('P2PKH Signature:', p2pkhSig.toString('base64')); // Sign for P2SH-P2WPKH address const p2shSig = BitcoinMessage.sign( message, privateKey, true, { segwitType: 'p2sh(p2wpkh)' } ); // Sign for P2WPKH address const p2wpkhSig = BitcoinMessage.sign( message, privateKey, true, { segwitType: 'p2wpkh' } ); // With additional entropy for randomized signing const entropyBuffer = Buffer.from('random_entropy_data'); const randomSig = BitcoinMessage.sign( message, privateKey, true, { extraEntropy: entropyBuffer } ); ``` -------------------------------- ### Example: Verifying a Bitcoin Message Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/BitcoinMessage.md Demonstrates how to verify a signature for different Bitcoin address types (P2PKH, P2SH-P2WPKH, P2WPKH). The function automatically detects the network from the address. ```typescript import { BitcoinMessage } from 'bip322-js'; const message = 'Hello World'; const address = 'bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l'; const signatureBase64 = 'IIABRVlp9vLOQ1SmBRtbZ7VkH9CUGqh48U...'; const isValid = BitcoinMessage.verify(message, address, signatureBase64); console.log('Signature Valid:', isValid); // Verify with different address types const p2pkhValid = BitcoinMessage.verify( message, '1A1z7agoat4bNpVauvBz6XwWjzJmdChAKn', signatureBase64 ); const p2shValid = BitcoinMessage.verify( message, '37qyp7jQAzqb2rCBpMvVtLDuuzKAUCVnJb', signatureBase64 ); ``` -------------------------------- ### Handle Failure to Compress Public Key Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/errors.md This example shows how to catch an error when the public key compression fails due to an invalid uncompressed public key. The input must be a valid 65-byte uncompressed public key. ```typescript import { Key } from 'bip322-js'; const invalidKey = Buffer.from('invalid_uncompressed_key'); try { Key.compressPublicKey(invalidKey); } catch (error) { console.error(error.message); // "Fails to compress the provided public key..." } ``` -------------------------------- ### Automatic Network Detection for Signing and Verification Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/configuration.md Demonstrates that network configuration is not required as the library automatically detects the network from the address format. This example shows signing and verifying messages across mainnet, testnet, and regtest addresses without explicit network settings. ```typescript import { Signer, Verifier, Address } from 'bip322-js'; const privateKey = 'L3VFeEujGtevx9w18HD1fhRbCH67Az2dpCymeRE1SoPK6XQtaN2k'; const message = 'Hello World'; // Just use addresses from different networks - detection is automatic const mainnetAddr = 'bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l'; // Detected as mainnet const testnetAddr = 'tb1q9vza2e8x573nczrlzms0wvx3gsqjx7vaxwd45v'; // Detected as testnet const regtestAddr = 'bcrt1q9vza2e8x573nczrlzms0wvx3gsqjx7vay85cr9'; // Detected as regtest // No configuration needed - network is automatically inferred const mainnetSig = Signer.sign(privateKey, mainnetAddr, message); const testnetSig = Signer.sign(privateKey, testnetAddr, message); const regtestSig = Signer.sign(privateKey, regtestAddr, message); // Verification works automatically on any network const mainnetValid = Verifier.verifySignature(mainnetAddr, message, mainnetSig); const testnetValid = Verifier.verifySignature(testnetAddr, message, testnetSig); const regtestValid = Verifier.verifySignature(regtestAddr, message, regtestSig); ``` -------------------------------- ### Handle Unsupported Address Types for BIP-322 Verification Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/errors.md This example shows how to handle errors when attempting BIP-322 verification with unsupported address types. Only P2WPKH, P2SH-P2WPKH, and single-key-spend P2TR are supported for BIP-322. ```typescript import { Verifier } from 'bip322-js'; const p2pkhAddress = '1A1z7agoat4bNpVauvBz6XwWjzJmdChAKn'; // Legacy address const bip322Signature = 'IIABRVlp9vL...'; // BIP-322 format try { // P2PKH addresses use BIP-137, not BIP-322 Verifier.verifySignature(p2pkhAddress, 'message', bip322Signature); // This will actually work because P2PKH is automatically detected as BIP-137 } catch (error) { console.error(error.message); } ``` -------------------------------- ### Handle Unknown Address Type Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/errors.md This example shows how to catch an 'Unknown address type' error when an unrecognized address format is provided to address conversion functions. This occurs if the address doesn't match any known Bitcoin address prefix. ```typescript import { Address } from 'bip322-js'; try { Address.getNetworkFromAddess('invalid_address'); } catch (error) { console.error(error.message); // "Unknown address type" } ``` -------------------------------- ### Decode DER-encoded Script Signature Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/DecodeScriptSignature.md Demonstrates how to use `decodeScriptSignature` to parse a DER-encoded signature. Includes example usage and error handling for invalid inputs. ```typescript import { decodeScriptSignature } from 'bip322-js'; // DER-encoded signature (typical format from Bitcoin transactions) const derSignature = Buffer.from( '3045022100' + // DER sequence header 'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789' + // R (32 bytes) '0223456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef' + // S (32 bytes) '01', // SIGHASH_ALL 'hex' ); const decoded = decodeScriptSignature(derSignature); console.log('Signature:', decoded.signature.toString('hex')); // 64-byte concat of R and S console.log('Sighash Type:', decoded.hashType); // 1 (SIGHASH_ALL) // The signature is in raw format (r + s), not DER-encoded console.log('Signature length:', decoded.signature.length); // 64 // Error handling try { const invalid = Buffer.from('invalid_der_data'); decodeScriptSignature(invalid); } catch (error) { console.error('Invalid DER signature:', error.message); } ``` -------------------------------- ### Build BIP322 To-Sign Transaction Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/BIP322.md Build a to_sign transaction that spends from the to_spend transaction. This transaction is what gets signed in the BIP-322 process. It returns a PSBT object ready for signing. ```typescript static buildToSignTx( toSpendTxId: string, witnessScript: Buffer, isRedeemScript: boolean = false, tapInternalKey: Buffer = undefined ): bitcoin.Psbt ``` ```typescript import { BIP322, Address } from 'bip322-js'; const message = 'Test message'; const address = 'bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l'; const scriptPubKey = Address.convertAdressToScriptPubkey(address); const toSpendTx = BIP322.buildToSpendTx(message, scriptPubKey); const toSpendTxId = toSpendTx.getId(); const toSignTx = BIP322.buildToSignTx(toSpendTxId, scriptPubKey); console.log('To Sign PSBT created, ready for signing'); ``` -------------------------------- ### isP2SH Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Checks if a given Bitcoin address is a pay-to-script-hash (P2SH) address. Identifies addresses starting with 3 (mainnet) or 2 (testnet). ```APIDOC ## isP2SH() ### Description Check if a given Bitcoin address is a pay-to-script-hash (P2SH) address. ### Method static isP2SH ### Parameters #### Path Parameters - **address** (string) - Required - Bitcoin address to be checked ### Response #### Success Response - **boolean** - True if the address is a P2SH address, false otherwise ### Example ```typescript import { Address } from 'bip322-js'; console.log(Address.isP2SH('37qyp7jQAzqb2rCBpMvVtLDuuzKAUCVnJb')); // true console.log(Address.isP2SH('2NEzrnyPEEt9JuaH6mVTN8u4r9NQ1p8K2qR')); // true console.log(Address.isP2SH('bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l')); // false ``` ``` -------------------------------- ### isP2PKH Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Checks if a given Bitcoin address is a pay-to-public-key-hash (P2PKH) address. Identifies addresses starting with 1 (mainnet), m (testnet), or n (testnet). ```APIDOC ## isP2PKH() ### Description Check if a given Bitcoin address is a pay-to-public-key-hash (P2PKH) address. ### Method static isP2PKH ### Parameters #### Path Parameters - **address** (string) - Required - Bitcoin address to be checked ### Response #### Success Response - **boolean** - True if the address is a P2PKH address, false otherwise ### Example ```typescript import { Address } from 'bip322-js'; console.log(Address.isP2PKH('1A1z7agoat4bNpVauvBz6XwWjzJmdChAKn')); // true console.log(Address.isP2PKH('mza7S5YK1n8Cg3a4p8J6N4V9Z8K1c7L6M')); // true console.log(Address.isP2PKH('bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l')); // false ``` ``` -------------------------------- ### Public Key Compression and Conversion Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/configuration.md Shows how to compress and uncompress public keys, and convert them to X-only format for Taproot. The `Key.compressPublicKey()` and `Key.uncompressPublicKey()` methods handle format detection automatically. ```typescript import { Key } from 'bip322-js'; // Compressed to uncompressed const compressed = Buffer.from('02abcd...', 'hex'); // 33 bytes const uncompressed = Key.uncompressPublicKey(compressed); // 65 bytes // Uncompressed to compressed const expanded = Buffer.from('04abcd...', 'hex'); // 65 bytes const compact = Key.compressPublicKey(expanded); // 33 bytes // X-only conversion (for Taproot) const xOnly = Key.toXOnly(compressed); // 32 bytes if input is 33 ``` -------------------------------- ### isP2TR Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Checks if a given Bitcoin address is a taproot (P2TR) address. Identifies taproot addresses starting with bc1p (mainnet), tb1p (testnet), or bcrt1p (regtest). ```APIDOC ## isP2TR() ### Description Check if a given Bitcoin address is a taproot (P2TR) address. ### Method static isP2TR ### Parameters #### Path Parameters - **address** (string) - Required - Bitcoin address to be checked ### Response #### Success Response - **boolean** - True if the address is a taproot address, false otherwise ### Example ```typescript import { Address } from 'bip322-js'; console.log(Address.isP2TR('bc1ppv609nr0vr25u07u95waq5lucwfm6tde4nydujnu8npg4q75mr5sxq8lt3')); // true console.log(Address.isP2TR('tb1ppv609nr0vr25u07u95waq5lucwfm6tde4nydujnu8npg4q75mr5sm5jc4h')); // true console.log(Address.isP2TR('bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l')); // false ``` ``` -------------------------------- ### Check if Address is P2SH Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Use this method to determine if a Bitcoin address is a Pay-to-Script-Hash (P2SH) address. It identifies addresses starting with '3' on mainnet or '2' on testnet. ```typescript import { Address } from 'bip322-js'; console.log(Address.isP2SH('37qyp7jQAzqb2rCBpMvVtLDuuzKAUCVnJb')); // true console.log(Address.isP2SH('2NEzrnyPEEt9JuaH6mVTN8u4r9NQ1p8K2qR')); // true console.log(Address.isP2SH('bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l')); // false ``` -------------------------------- ### Address Conversion for Different Types Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/configuration.md Illustrates how to convert a public key into addresses for various supported types (P2PKH, P2SH, P2WPKH, P2TR) across different networks (mainnet, testnet, regtest). The `Address.convertPubKeyIntoAddress()` method requires an address type parameter. ```typescript import { Address } from 'bip322-js'; const publicKey = Buffer.from('...', 'hex'); // Generate addresses for all supported types const p2pkh = Address.convertPubKeyIntoAddress(publicKey, 'p2pkh'); const p2sh = Address.convertPubKeyIntoAddress(publicKey, 'p2sh-p2wpkh'); const p2wpkh = Address.convertPubKeyIntoAddress(publicKey, 'p2wpkh'); const p2tr = Address.convertPubKeyIntoAddress(publicKey, 'p2tr'); // Each returns addresses for all networks console.log('Mainnet P2PKH:', p2pkh.mainnet); // 1... console.log('Testnet P2PKH:', p2pkh.testnet); // m... or n... console.log('Regtest P2PKH:', p2pkh.regtest); // m... or n... ``` -------------------------------- ### Construct BIP-322 toSpend and toSign Transactions Source: https://github.com/acken2/bip322-js/blob/main/README.md Shows how to build the raw unsigned BIP-322 toSpend transaction and the corresponding toSign PSBT using the message and script public key. This is useful for advanced use cases where direct transaction manipulation is needed. ```javascript const { BIP322 } = require('bip322-js'); const scriptPubKey = Buffer.from('00142b05d564e6a7a33c087f16e0f730d1440123799d', 'hex'); const message = 'Hello World'; const toSpend = BIP322.buildToSpendTx(message, scriptPubKey); // bitcoin.Transaction const toSpendTxId = toSpend.getId(); const toSign = BIP322.buildToSignTx(toSpendTxId, scriptPubKey); // bitcoin.Psbt // Do whatever you want to do with the PSBT ``` -------------------------------- ### Check if Address is P2PKH Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Use this method to determine if a Bitcoin address is a Pay-to-Public-Key-Hash (P2PKH) address. It identifies addresses starting with '1' on mainnet or 'm'/'n' on testnet. ```typescript import { Address } from 'bip322-js'; console.log(Address.isP2PKH('1A1z7agoat4bNpVauvBz6XwWjzJmdChAKn')); // true console.log(Address.isP2PKH('mza7S5YK1n8Cg3a4p8J6N4V9Z8K1c7L6M')); // true console.log(Address.isP2PKH('bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l')); // false ``` -------------------------------- ### Deterministic vs. Non-Deterministic Signing Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/configuration.md Demonstrates how to sign messages deterministically (default) and non-deterministically using extra entropy. Deterministic signing ensures the same message and key always produce the same signature, while non-deterministic signing allows for unique signatures per signing operation. ```typescript import { BitcoinMessage } from 'bip322-js'; import { randomBytes } from 'crypto'; const privateKey = Buffer.from('...', 'hex'); const message = 'Hello World'; // Deterministic signing (RFC 6979) - default // Same message + key always produces same signature const sig1 = BitcoinMessage.sign(message, privateKey, true); const sig2 = BitcoinMessage.sign(message, privateKey, true); console.log('Same signature:', sig1.equals(sig2)); // true // Non-deterministic signing with extra entropy // Same message + key produces different signatures each time const entropy = randomBytes(32); const sig3 = BitcoinMessage.sign( message, privateKey, true, { extraEntropy: entropy } ); const sig4 = BitcoinMessage.sign( message, privateKey, true, { extraEntropy: randomBytes(32) } ); console.log('Different signatures:', !sig3.equals(sig4)); // true ``` -------------------------------- ### isP2WPKH Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Checks if a given Bitcoin address is a pay-to-witness-public-key-hash (P2WPKH) address. Identifies native SegWit addresses starting with bc1q (mainnet), tb1q (testnet), or bcrt1q (regtest). ```APIDOC ## isP2WPKH() ### Description Check if a given Bitcoin address is a pay-to-witness-public-key-hash (P2WPKH) address. ### Method static isP2WPKH ### Parameters #### Path Parameters - **address** (string) - Required - Bitcoin address to be checked ### Response #### Success Response - **boolean** - True if the address is a P2WPKH address, false otherwise ### Example ```typescript import { Address } from 'bip322-js'; console.log(Address.isP2WPKH('bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l')); // true console.log(Address.isP2WPKH('tb1q9vza2e8x573nczrlzms0wvx3gsqjx7vaxwd45v')); // true console.log(Address.isP2WPKH('bc1qwqdg6squsna38e46795at95yu9atm8azzmqecjhee28h7gv96m5')); // false (P2WSH) ``` ``` -------------------------------- ### Check if Address is P2TR Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Use this method to determine if a Bitcoin address is a Taproot (P2TR) address. It identifies addresses starting with 'bc1p' (mainnet), 'tb1p' (testnet), or 'bcrt1p' (regtest). ```typescript import { Address } from 'bip322-js'; console.log(Address.isP2TR('bc1ppv609nr0vr25u07u95waq5lucwfm6tde4nydujnu8npg4q75mr5sxq8lt3')); // true console.log(Address.isP2TR('tb1ppv609nr0vr25u07u95waq5lucwfm6tde4nydujnu8npg4q75mr5sm5jc4h')); // true console.log(Address.isP2TR('bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l')); // false ``` -------------------------------- ### Sign Bitcoin Message with Options Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/types.md Demonstrates signing a Bitcoin message using different segwit types and with additional entropy. Defaults to legacy P2PKH if segwitType is omitted. ```typescript import { BitcoinMessage } from 'bip322-js'; const privateKey = Buffer.from('...', 'hex'); const message = 'Hello World'; // Legacy P2PKH signing (default) const legacySig = BitcoinMessage.sign(message, privateKey, true); // Nested Segwit signing with header type const nestedSig = BitcoinMessage.sign( message, privateKey, true, { segwitType: 'p2sh(p2wpkh)' } ); // Native Segwit signing const nativeSig = BitcoinMessage.sign( message, privateKey, true, { segwitType: 'p2wpkh' } ); // With additional entropy for randomized signatures const randomSig = BitcoinMessage.sign( message, privateKey, true, { extraEntropy: Buffer.from('random_bytes') } ); ``` -------------------------------- ### buildToSpendTx() Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/BIP322.md Constructs the initial 'to_spend' transaction required for the BIP-322 signing process. This transaction is based on the message and the script public key of the signing wallet. ```APIDOC ## buildToSpendTx() ### Description Build a to_spend transaction for simple signature BIP-322 signing. This is the first transaction in the BIP-322 signing process. ### Method static buildToSpendTx ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **message** (string | Buffer) - Required - Message to be signed using BIP-322 - **scriptPublicKey** (Buffer) - Required - The script public key for the signing wallet ### Returns `bitcoin.Transaction` - A Bitcoin transaction object that corresponds to the to_spend transaction. The transaction has version 0, locktime 0, and contains the message hash in the scriptSig. ### Throws Error if scriptPublicKey is invalid or missing ### Example ```typescript import { BIP322, Address } from 'bip322-js'; const message = 'Test message'; const address = 'bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l'; const scriptPubKey = Address.convertAdressToScriptPubkey(address); const toSpendTx = BIP322.buildToSpendTx(message, scriptPubKey); const txId = toSpendTx.getId(); console.log('To Spend TX ID:', txId); ``` ``` -------------------------------- ### Sign and Verify BIP-322 Signatures Source: https://github.com/acken2/bip322-js/blob/main/README.md Demonstrates signing a message with a private key and verifying the signature against different address types (P2WPKH, P2TR, P2SH-P2WPKH) on mainnet, testnet, and regtest. The network is automatically inferred from the address. ```javascript const { BIP322, Signer, Verifier } = require('bip322-js'); const privateKey = 'L3VFeEujGtevx9w18HD1fhRbCH67Az2dpCymeRE1SoPK6XQtaN2k'; const address = 'bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l'; // P2WPKH address const addressTestnet = 'tb1q9vza2e8x573nczrlzms0wvx3gsqjx7vaxwd45v'; // Equivalent testnet address const addressRegtest = 'bcrt1q9vza2e8x573nczrlzms0wvx3gsqjx7vay85cr9'; // Equivalent regtest address const taprootAddress = 'bc1ppv609nr0vr25u07u95waq5lucwfm6tde4nydujnu8npg4q75mr5sxq8lt3'; // P2TR address const nestedSegwitAddress = '37qyp7jQAzqb2rCBpMvVtLDuuzKAUCVnJb'; // P2SH-P2WPKH address const message = 'Hello World'; const signature = Signer.sign(privateKey, address, message); const signatureTestnet = Signer.sign(privateKey, addressTestnet, message); // Wworks with testnet address const signatureRegtest = Signer.sign(privateKey, addressRegtest, message); // And regtest address const signatureP2TR = Signer.sign(privateKey, taprootAddress, message); // Also works with P2TR address const signatureP2SH = Signer.sign(privateKey, nestedSegwitAddress, message); // And P2SH-P2WPKH address console.log({ signature, signatureTestnet, signatureRegtest, signatureP2TR, signatureP2SH }); const validity = Verifier.verifySignature(address, message, signature); const validityTestnet = Verifier.verifySignature(addressTestnet, message, signatureTestnet); // Works with testnet address const validityRegtest = Verifier.verifySignature(addressRegtest, message, signatureRegtest); // And regtest address const validityP2TR = Verifier.verifySignature(taprootAddress, message, signatureP2TR); // Also works with P2TR address const validityP2SH = Verifier.verifySignature(nestedSegwitAddress, message, signatureP2SH); // And P2SH-P2WPKH address console.log({ validity, validityTestnet, validityRegtest, validityP2TR, validityP2SH }); // True ``` -------------------------------- ### Check if Address is P2WPKH Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Use this method to determine if a Bitcoin address is a native Pay-to-Witness-Public-Key-Hash (P2WPKH) address. It identifies addresses starting with 'bc1q' (mainnet), 'tb1q' (testnet), or 'bcrt1q' (regtest). ```typescript import { Address } from 'bip322-js'; console.log(Address.isP2WPKH('bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l')); // true console.log(Address.isP2WPKH('tb1q9vza2e8x573nczrlzms0wvx3gsqjx7vaxwd45v')); // true console.log(Address.isP2WPKH('bc1qwqdg6squsna38e46795at95yu9atm8azzmqecjhee28h7gv96m5')); // false (P2WSH) ``` -------------------------------- ### buildToSignTx() Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/BIP322.md Creates a 'to_sign' transaction, which is derived from the 'to_spend' transaction and is the actual transaction that will be signed during the BIP-322 process. It can optionally include Taproot-specific data. ```APIDOC ## buildToSignTx() ### Description Build a to_sign transaction that spends from the to_spend transaction. This transaction is what gets signed in the BIP-322 process. ### Method static buildToSignTx ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **toSpendTxId** (string) - Required - Transaction ID of the to_spend transaction - **witnessScript** (Buffer) - Required - The script public key for the signing wallet, or the redeemScript for P2SH-P2WPKH address - **isRedeemScript** (boolean) - Optional - Set to true if the provided witnessScript is a redeemScript for P2SH-P2WPKH address. Defaults to false. - **tapInternalKey** (Buffer) - Optional - Used to set the taproot internal public key when provided. Defaults to undefined. ### Returns `bitcoin.Psbt` - A ready-to-be-signed bitcoinjs PSBT transaction object ### Throws Error if transaction ID is invalid ### Example ```typescript import { BIP322, Address } from 'bip322-js'; const message = 'Test message'; const address = 'bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l'; const scriptPubKey = Address.convertAdressToScriptPubkey(address); const toSpendTx = BIP322.buildToSpendTx(message, scriptPubKey); const toSpendTxId = toSpendTx.getId(); const toSignTx = BIP322.buildToSignTx(toSpendTxId, scriptPubKey); console.log('To Sign PSBT created, ready for signing'); ``` ``` -------------------------------- ### Convert Public Key to Bitcoin Addresses Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Generates mainnet, testnet, and regtest addresses from a public key for specified address types (P2PKH, P2SH-P2WPKH, P2WPKH, P2TR). Throws an error for unsupported address types. ```typescript static convertPubKeyIntoAddress( publicKey: Buffer, addressType: 'p2pkh' | 'p2sh-p2wpkh' | 'p2wpkh' | 'p2tr' ): { mainnet: string; testnet: string; regtest: string } ``` ```typescript import { Address } from 'bip322-js'; const publicKey = Buffer.from('02...compressed_public_key...', 'hex'); // Generate P2PKH addresses const p2pkhAddresses = Address.convertPubKeyIntoAddress(publicKey, 'p2pkh'); console.log('P2PKH Mainnet:', p2pkhAddresses.mainnet); console.log('P2PKH Testnet:', p2pkhAddresses.testnet); // Generate P2SH-P2WPKH addresses const p2shAddresses = Address.convertPubKeyIntoAddress(publicKey, 'p2sh-p2wpkh'); // Generate P2WPKH addresses const p2wpkhAddresses = Address.convertPubKeyIntoAddress(publicKey, 'p2wpkh'); // Generate P2TR addresses (public key will be converted to x-only) const p2trAddresses = Address.convertPubKeyIntoAddress(publicKey, 'p2tr'); ``` -------------------------------- ### convertPubKeyIntoAddress Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Converts a public key into a Bitcoin address of the specified type for mainnet, testnet, and regtest. Throws an error if the address type is unsupported. ```APIDOC ## convertPubKeyIntoAddress(publicKey: Buffer, addressType: 'p2pkh' | 'p2sh-p2wpkh' | 'p2wpkh' | 'p2tr') ### Description Converts a public key into a Bitcoin address of the specified type for mainnet, testnet, and regtest. Throws an error if the address type is unsupported. ### Method Signature `static convertPubKeyIntoAddress( publicKey: Buffer, addressType: 'p2pkh' | 'p2sh-p2wpkh' | 'p2wpkh' | 'p2tr' ): { mainnet: string; testnet: string; regtest: string }` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | publicKey | Buffer | Yes | — | Public key for deriving the address, or internal public key for P2TR | | addressType | string | Yes | — | Bitcoin address type: 'p2pkh', 'p2sh-p2wpkh', 'p2wpkh', or 'p2tr' | ### Returns `object` — Object with mainnet, testnet, and regtest addresses ```json { mainnet: string; testnet: string; regtest: string; } ``` ### Throws Error if addressType is unsupported ### Example ```typescript import { Address } from 'bip322-js'; const publicKey = Buffer.from('02...compressed_public_key...', 'hex'); // Generate P2PKH addresses const p2pkhAddresses = Address.convertPubKeyIntoAddress(publicKey, 'p2pkh'); console.log('P2PKH Mainnet:', p2pkhAddresses.mainnet); console.log('P2PKH Testnet:', p2pkhAddresses.testnet); // Generate P2SH-P2WPKH addresses const p2shAddresses = Address.convertPubKeyIntoAddress(publicKey, 'p2sh-p2wpkh'); // Generate P2WPKH addresses const p2wpkhAddresses = Address.convertPubKeyIntoAddress(publicKey, 'p2wpkh'); // Generate P2TR addresses (public key will be converted to x-only) const p2trAddresses = Address.convertPubKeyIntoAddress(publicKey, 'p2tr'); ``` ``` -------------------------------- ### convertAdressToScriptPubkey Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Address.md Converts a given Bitcoin address into its corresponding script public key (scriptPubKey). Throws an error if the address is not valid. ```APIDOC ## convertAdressToScriptPubkey(address: string) ### Description Converts a given Bitcoin address into its corresponding script public key (scriptPubKey). Throws an error if the address is not valid. ### Method Signature `static convertAdressToScriptPubkey(address: string): Buffer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | address | string | Yes | — | Bitcoin address | ### Returns `Buffer` — Script public key of the given Bitcoin address ### Throws Error if the address is not a valid Bitcoin address ### Example ```typescript import { Address } from 'bip322-js'; const p2pkhAddress = '1A1z7agoat4bNpVauvBz6XwWjzJmdChAKn'; const scriptPubKey = Address.convertAdressToScriptPubkey(p2pkhAddress); console.log('ScriptPubKey:', scriptPubKey.toString('hex')); // Works with all supported address types const p2wpkhScriptPubKey = Address.convertAdressToScriptPubkey('bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l'); const p2trScriptPubKey = Address.convertAdressToScriptPubkey('bc1ppv609nr0vr25u07u95waq5lucwfm6tde4nydujnu8npg4q75mr5sxq8lt3'); ``` ``` -------------------------------- ### Compress and Uncompress Public Keys Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/README.md The Key class provides functions to compress uncompressed public keys into their 33-byte compressed form and to uncompress them back. It also supports converting keys to the 32-byte x-only format for Taproot. ```typescript import { Key } from 'bip322-js'; // Compress an uncompressed key const uncompressed = Buffer.from('04abcd...', 'hex'); // 65 bytes const compressed = Key.compressPublicKey(uncompressed); // 33 bytes // Uncompress a compressed key const expanded = Key.uncompressPublicKey(compressed); // 65 bytes // Convert to x-only (Taproot) const xOnly = Key.toXOnly(compressed); // 32 bytes ``` -------------------------------- ### Manually Build BIP322 Transactions Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/README.md Construct the necessary transactions for BIP-322 signing using the BIP322 class. This involves creating a 'to_spend' transaction and then a 'to_sign' transaction ready for signing. ```typescript import { BIP322, Address } from 'bip322-js'; const message = 'Test message'; const address = 'bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l'; const scriptPubKey = Address.convertAdressToScriptPubkey(address); // Create to_spend transaction const toSpendTx = BIP322.buildToSpendTx(message, scriptPubKey); const toSpendTxId = toSpendTx.getId(); // Create to_sign transaction (ready for signing) const toSignTx = BIP322.buildToSignTx(toSpendTxId, scriptPubKey); // Sign and extract witness... ``` -------------------------------- ### Handle Failure to Uncompress Public Key Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/errors.md This snippet demonstrates catching an error when uncompressing a public key fails due to an invalid compressed public key. The input must be a valid 33-byte compressed public key. ```typescript import { Key } from 'bip322-js'; const invalidKey = Buffer.from('invalid_compressed_key'); try { Key.uncompressPublicKey(invalidKey); } catch (error) { console.error(error.message); // "Fails to uncompress the provided public key..." } ``` -------------------------------- ### toXOnly() Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Key.md Converts a Bitcoin public key to a 32-byte x-only public key, essential for Taproot compatibility (BIP-341). It handles both 32-byte and 33-byte inputs, returning the 32-byte x-coordinate. ```APIDOC ## toXOnly() ### Description Converts a Bitcoin public key to a 32-byte x-only public key for use with Taproot (BIP-341). ### Method `static toXOnly(publicKey: Buffer): Buffer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **publicKey** (Buffer) - Required - 32-byte or 33-byte public key buffer ### Returns - **Buffer** - A 32-byte x-only public key ### Behavior - If input is 32 bytes: returns the buffer unchanged - If input is 33 bytes: removes the first byte (parity indicator) and returns the remaining 32 bytes - The first byte of a 33-byte compressed key indicates the y-coordinate parity (0x02 or 0x03) ### Throws Error if the public key is neither 32-byte nor 33-byte long ### Example ```typescript import { Key } from 'bip322-js'; // From a 33-byte compressed public key const compressedKey = Buffer.from('02abcdef...', 'hex'); // 33 bytes const xOnlyKey = Key.toXOnly(compressedKey); console.log('X-Only Key:', xOnlyKey.toString('hex')); // 32 bytes // From a 32-byte x-only key const alreadyXOnly = Buffer.from('abcdef...', 'hex'); // 32 bytes const result = Key.toXOnly(alreadyXOnly); console.log('Unchanged:', result.toString('hex')); ``` ``` -------------------------------- ### Sign a Message with BIP322-JS Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/README.md Use the Signer class to generate a BIP-322 signature for a given message, private key, and address. The signature is returned in Base64 encoding. ```typescript import { Signer } from 'bip322-js'; const privateKey = 'L3VFeEujGtevx9w18HD1fhRbCH67Az2dpCymeRE1SoPK6XQtaN2k'; const address = 'bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l'; const message = 'Hello World'; const signature = Signer.sign(privateKey, address, message); console.log('Signature:', signature); // Base64-encoded BIP-322 signature ``` -------------------------------- ### Convert Public Key to X-Only Format (TypeScript) Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Key.md Converts a 32-byte or 33-byte public key buffer to a 32-byte x-only public key, essential for Taproot compatibility. Handles both 32-byte inputs (returning them unchanged) and 33-byte inputs (removing the parity byte). ```typescript import { Key } from 'bip322-js'; // From a 33-byte compressed public key const compressedKey = Buffer.from('02abcdef...', 'hex'); // 33 bytes const xOnlyKey = Key.toXOnly(compressedKey); console.log('X-Only Key:', xOnlyKey.toString('hex')); // 32 bytes // From a 32-byte x-only key const alreadyXOnly = Buffer.from('abcdef...', 'hex'); // 32 bytes const result = Key.toXOnly(alreadyXOnly); console.log('Unchanged:', result.toString('hex')); ``` -------------------------------- ### compressPublicKey() Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Key.md Compresses an uncompressed 65-byte public key into a 33-byte compressed format using the secp256k1 elliptic curve. This is useful for reducing data size while retaining necessary information. ```APIDOC ## compressPublicKey() ### Description Compress an uncompressed (65-byte) public key using the secp256k1 elliptic curve. ### Method `static compressPublicKey(uncompressedPublicKey: Buffer): Buffer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **uncompressedPublicKey** (Buffer) - Required - A 65-byte uncompressed public key buffer ### Returns - **Buffer** - A 33-byte compressed public key buffer ### Format - Input: 65 bytes (0x04 prefix + 32 bytes X + 32 bytes Y) - Output: 33 bytes (0x02 or 0x03 prefix + 32 bytes X) ### Throws Error if the public key cannot be compressed (invalid key) ### Example ```typescript import { Key } from 'bip322-js'; // Uncompressed public key (65 bytes) const uncompressed = Buffer.from('04abcdef...', 'hex'); const compressed = Key.compressPublicKey(uncompressed); console.log('Compressed:', compressed.toString('hex')); // 33 bytes console.log('Length:', compressed.length); // 33 // Error handling try { const invalid = Buffer.from('invalid_key'); Key.compressPublicKey(invalid); } catch (error) { console.error('Invalid public key:', error.message); } ``` ``` -------------------------------- ### Convert Public Key to Bitcoin Address Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/README.md Utilize the Address class to convert a public key into various Bitcoin address formats, including mainnet, testnet, and regtest for P2WPKH addresses. ```typescript import { Address } from 'bip322-js'; const publicKey = Buffer.from('02abcd...', 'hex'); // Generate addresses for all types const addresses = Address.convertPubKeyIntoAddress(publicKey, 'p2wpkh'); console.log('Mainnet:', addresses.mainnet); console.log('Testnet:', addresses.testnet); console.log('Regtest:', addresses.regtest); ``` -------------------------------- ### Select Address by Network Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/types.md Retrieves Bitcoin addresses for mainnet, testnet, and regtest from an AddressResult object. Allows dynamic selection of the appropriate network address. ```typescript import { Address } from 'bip322-js'; const publicKey = Buffer.from('...', 'hex'); const addresses = Address.convertPubKeyIntoAddress(publicKey, 'p2wpkh'); console.log('Mainnet address:', addresses.mainnet); // bc1... console.log('Testnet address:', addresses.testnet); // tb1... console.log('Regtest address:', addresses.regtest); // bcrt1... // Use the correct address based on the network you're working with const currentNetwork = 'testnet'; // or 'mainnet', 'regtest' const addressForNetwork = addresses[currentNetwork]; ``` -------------------------------- ### uncompressPublicKey() Source: https://github.com/acken2/bip322-js/blob/main/_autodocs/api-reference/Key.md Uncompresses a compressed 33-byte public key into its original 65-byte uncompressed format using the secp256k1 elliptic curve. This is useful when the full X and Y coordinates are needed. ```APIDOC ## uncompressPublicKey() ### Description Uncompress a compressed (33-byte) public key using the secp256k1 elliptic curve. ### Method `static uncompressPublicKey(compressedPublicKey: Buffer): Buffer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **compressedPublicKey** (Buffer) - Required - A 33-byte compressed public key buffer ### Returns - **Buffer** - A 65-byte uncompressed public key buffer ### Format - Input: 33 bytes (0x02 or 0x03 prefix + 32 bytes X) - Output: 65 bytes (0x04 prefix + 32 bytes X + 32 bytes Y) ### Throws Error if the public key cannot be uncompressed (invalid key) ### Example ```typescript import { Key } from 'bip322-js'; // Compressed public key (33 bytes) const compressed = Buffer.from('02abcdef...', 'hex'); const uncompressed = Key.uncompressPublicKey(compressed); console.log('Uncompressed:', uncompressed.toString('hex')); // 65 bytes console.log('Length:', uncompressed.length); // 65 // Error handling try { const invalid = Buffer.from('invalid_key'); Key.uncompressPublicKey(invalid); } catch (error) { console.error('Invalid public key:', error.message); } ``` ```