Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@exodus/bitcoinjs-lib

Package Overview
Dependencies
Maintainers
100
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@exodus/bitcoinjs-lib - npm Package Compare versions

Comparing version 6.1.5-exodus.2 to 6.1.6-exodus.0

6

package.json
{
"name": "@exodus/bitcoinjs-lib",
"version": "6.1.5-exodus.2",
"version": "6.1.6-exodus.0",
"description": "Client-side Bitcoin JavaScript library",

@@ -26,2 +26,3 @@ "main": "./src/index.js",

"coverage": "npm run build && npm run nobuild:coverage",
"doc": "typedoc",
"format": "npm run prettier -- --write",

@@ -83,3 +84,3 @@ "formatjs": "npm run prettierjs -- --write",

"minimaldata": "^1.0.2",
"mocha": "^10.0.0",
"mocha": "^10.6.0",
"nyc": "^15.1.0",

@@ -93,2 +94,3 @@ "prettier": "^2.8.0",

"ts-node": "^8.3.0",
"typedoc": "^0.25.1",
"typescript": "^4.4.4"

@@ -95,0 +97,0 @@ },

@@ -1,2 +0,7 @@

# BitcoinJS (bitcoinjs-lib)
<img src="./logo/Bitcoin.js-transparent.png" alt="BitcoinJS kawaii logo" width="50%" />
(Logo by [@sawaratsuki1004](https://x.com/sawaratsuki1004))
([LICENSE for the logo is on SAWARATSUKI Github repo](https://github.com/SAWARATSUKI/KawaiiLogos/blob/main/README_EN.md))
[![Github CI](https://github.com/bitcoinjs/bitcoinjs-lib/actions/workflows/main_ci.yml/badge.svg)](https://github.com/bitcoinjs/bitcoinjs-lib/actions/workflows/main_ci.yml) [![NPM](https://img.shields.io/npm/v/bitcoinjs-lib.svg)](https://www.npmjs.org/package/bitcoinjs-lib) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)

@@ -26,3 +31,3 @@

## Documentation
Presently, we do not have any formal documentation other than our [examples](#examples), please [ask for help](https://github.com/bitcoinjs/bitcoinjs-lib/issues/new) if our examples aren't enough to guide you.
Visit our [documentation](https://bitcoinjs.github.io/bitcoinjs-lib/) to explore the available resources. We're continually enhancing our documentation with additional features for an enriched experience. If you need further guidance beyond what our [examples](#examples) offer, don't hesitate to [ask for help](https://github.com/bitcoinjs/bitcoinjs-lib/issues/new). We're here to assist you.

@@ -97,3 +102,3 @@ You can find a [Web UI](https://bitcoincore.tech/apps/bitcoinjs-ui/index.html) that covers most of the `psbt.ts`, `transaction.ts` and `p2*.ts` APIs [here](https://bitcoincore.tech/apps/bitcoinjs-ui/index.html).

$ npm install bitcoinjs-lib browserify
$ npx browserify --standalone bitcoin - -o bitcoinjs-lib.js <<<"module.exports = require('bitcoinjs-lib');"
$ npx browserify --standalone bitcoin -o bitcoinjs-lib.js <<< "module.exports = require('bitcoinjs-lib');"
```

@@ -107,2 +112,12 @@

#### Using Taproot:
When utilizing Taproot features with bitcoinjs-lib, you may need to include an additional ECC (Elliptic Curve Cryptography) library. The commonly used `tiny-secp256k1` library, however, might lead to compatibility issues due to its reliance on WASM (WebAssembly). The following alternatives may be used instead, though they may be significantly slower for high volume of signing and pubkey deriving operations.
#### Alternatives for ECC Library:
1. `@bitcoinjs-lib/tiny-secp256k1-asmjs`
A version of `tiny-secp256k1` compiled to ASM.js directly from the WASM version, potentially better supported in browsers. This is the slowest option.
2. `@bitcoinerlab/secp256k1`
Another alternative library for ECC functionality. This requires access to the global `BigInt` primitive.
For advantages and detailed comparison of these libraries, visit: [tiny-secp256k1 GitHub page](https://github.com/bitcoinjs/tiny-secp256k1).
**NOTE**: We use Node Maintenance LTS features, if you need strict ES5, use [`--transform babelify`](https://github.com/babel/babelify) in conjunction with your `browserify` step (using an [`es2015`](https://babeljs.io/docs/plugins/preset-es2015/) preset).

@@ -122,2 +137,5 @@

- [Taproot Key Spend](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/taproot.spec.ts)
- [Create (and broadcast via 3PBP) a taproot script-path spend Transaction - OP_CHECKSIG](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/taproot.spec.ts)
- [Create (and broadcast via 3PBP) a taproot script-path spend Transaction - OP_CHECKSEQUENCEVERIFY](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/taproot.spec.ts)
- [Create (and broadcast via 3PBP) a taproot script-path spend Transaction - OP_CHECKSIGADD (3-of-3)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/taproot.spec.ts)
- [Generate a random address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts)

@@ -124,0 +142,0 @@ - [Import an address via WIF](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.spec.ts)

/// <reference types="node" />
/**
* bitcoin address decode and encode tools, include base58、bech32 and output script
*
* networks support bitcoin、bitcoin testnet and bitcoin regtest
*
* addresses support P2PKH、P2SH、P2WPKH、P2WSH、P2TR and so on
*
* @packageDocumentation
*/
import { Network } from './networks';
/** base58check decode result */
export interface Base58CheckResult {
/** address hash */
hash: Buffer;
/** address version: 0x00 for P2PKH, 0x05 for P2SH */
version: number;
}
/** bech32 decode result */
export interface Bech32Result {
/** address version: 0x00 for P2WPKH、P2WSH, 0x01 for P2TR*/
version: number;
/** address prefix: bc for P2WPKH、P2WSH、P2TR */
prefix: string;
/** address data:20 bytes for P2WPKH, 32 bytes for P2WSH、P2TR */
data: Buffer;
}
/**
* Decodes a base58check encoded Bitcoin address and returns the version and hash.
*
* @param address - The base58check encoded Bitcoin address to decode.
* @returns An object containing the version and hash of the decoded address.
* @throws {TypeError} If the address is too short or too long.
*/
export declare function fromBase58Check(address: string): Base58CheckResult;
/**
* Converts a Bech32 or Bech32m encoded address to its corresponding data representation.
* @param address - The Bech32 or Bech32m encoded address.
* @returns An object containing the version, prefix, and data of the address.
* @throws {TypeError} If the address uses the wrong encoding.
*/
export declare function fromBech32(address: string): Bech32Result;
/**
* Converts a hash to a Base58Check-encoded string.
* @param hash - The hash to be encoded.
* @param version - The version byte to be prepended to the encoded string.
* @returns The Base58Check-encoded string.
*/
export declare function toBase58Check(hash: Buffer, version: number): string;
/**
* Converts a buffer to a Bech32 or Bech32m encoded string.
* @param data - The buffer to be encoded.
* @param version - The version number to be used in the encoding.
* @param prefix - The prefix string to be used in the encoding.
* @returns The Bech32 or Bech32m encoded string.
*/
export declare function toBech32(data: Buffer, version: number, prefix: string): string;
/**
* Converts an output script to a Bitcoin address.
* @param output - The output script as a Buffer.
* @param network - The Bitcoin network (optional).
* @returns The Bitcoin address corresponding to the output script.
* @throws If the output script has no matching address.
*/
export declare function fromOutputScript(output: Buffer, network?: Network): string;
/**
* Converts a Bitcoin address to its corresponding output script.
* @param address - The Bitcoin address to convert.
* @param network - The Bitcoin network to use. Defaults to the Bitcoin network.
* @returns The corresponding output script as a Buffer.
* @throws If the address has an invalid prefix or no matching script.
*/
export declare function toOutputScript(address: string, network?: Network): Buffer;

@@ -26,2 +26,9 @@ 'use strict';

'then decide when it is safe to use which version of segwit.';
/**
* Converts an output buffer to a future segwit address.
* @param output - The output buffer.
* @param network - The network object.
* @returns The future segwit address.
* @throws {TypeError} If the program length or version is invalid for segwit address.
*/
function _toFutureSegwitAddress(output, network) {

@@ -45,2 +52,9 @@ const data = output.slice(2);

}
/**
* Decodes a base58check encoded Bitcoin address and returns the version and hash.
*
* @param address - The base58check encoded Bitcoin address to decode.
* @returns An object containing the version and hash of the decoded address.
* @throws {TypeError} If the address is too short or too long.
*/
function fromBase58Check(address) {

@@ -56,2 +70,8 @@ const payload = Buffer.from(bs58check.decode(address));

exports.fromBase58Check = fromBase58Check;
/**
* Converts a Bech32 or Bech32m encoded address to its corresponding data representation.
* @param address - The Bech32 or Bech32m encoded address.
* @returns An object containing the version, prefix, and data of the address.
* @throws {TypeError} If the address uses the wrong encoding.
*/
function fromBech32(address) {

@@ -79,2 +99,8 @@ let result;

exports.fromBech32 = fromBech32;
/**
* Converts a hash to a Base58Check-encoded string.
* @param hash - The hash to be encoded.
* @param version - The version byte to be prepended to the encoded string.
* @returns The Base58Check-encoded string.
*/
function toBase58Check(hash, version) {

@@ -91,2 +117,9 @@ (0, types_1.typeforce)(

exports.toBase58Check = toBase58Check;
/**
* Converts a buffer to a Bech32 or Bech32m encoded string.
* @param data - The buffer to be encoded.
* @param version - The version number to be used in the encoding.
* @param prefix - The prefix string to be used in the encoding.
* @returns The Bech32 or Bech32m encoded string.
*/
function toBech32(data, version, prefix) {

@@ -100,2 +133,9 @@ const words = bech32_1.bech32.toWords(data);

exports.toBech32 = toBech32;
/**
* Converts an output script to a Bitcoin address.
* @param output - The output script as a Buffer.
* @param network - The Bitcoin network (optional).
* @returns The Bitcoin address corresponding to the output script.
* @throws If the output script has no matching address.
*/
function fromOutputScript(output, network) {

@@ -125,2 +165,9 @@ // TODO: Network

exports.fromOutputScript = fromOutputScript;
/**
* Converts a Bitcoin address to its corresponding output script.
* @param address - The Bitcoin address to convert.
* @param network - The Bitcoin network to use. Defaults to the Bitcoin network.
* @returns The corresponding output script as a Buffer.
* @throws If the address has an invalid prefix or no matching script.
*/
function toOutputScript(address, network) {

@@ -127,0 +174,0 @@ network = network || networks.bitcoin;

/// <reference types="node" />
/**
* Checks if the given buffer is a valid BIP66-encoded signature.
*
* @param buffer - The buffer to check.
* @returns A boolean indicating whether the buffer is a valid BIP66-encoded signature.
*/
export declare function check(buffer: Buffer): boolean;
/**
* Decodes a DER-encoded signature buffer and returns the R and S values.
* @param buffer - The DER-encoded signature buffer.
* @returns An object containing the R and S values.
* @throws {Error} If the DER sequence length is too short, too long, or invalid.
* @throws {Error} If the R or S length is zero or invalid.
* @throws {Error} If the R or S value is negative or excessively padded.
*/
export declare function decode(buffer: Buffer): {

@@ -4,0 +18,0 @@ r: Buffer;

@@ -7,2 +7,8 @@ 'use strict';

exports.encode = exports.decode = exports.check = void 0;
/**
* Checks if the given buffer is a valid BIP66-encoded signature.
*
* @param buffer - The buffer to check.
* @returns A boolean indicating whether the buffer is a valid BIP66-encoded signature.
*/
function check(buffer) {

@@ -29,2 +35,10 @@ if (buffer.length < 8) return false;

exports.check = check;
/**
* Decodes a DER-encoded signature buffer and returns the R and S values.
* @param buffer - The DER-encoded signature buffer.
* @returns An object containing the R and S values.
* @throws {Error} If the DER sequence length is too short, too long, or invalid.
* @throws {Error} If the R or S length is zero or invalid.
* @throws {Error} If the R or S value is negative or excessively padded.
*/
function decode(buffer) {

@@ -31,0 +45,0 @@ if (buffer.length < 8) throw new Error('DER sequence length is too short');

@@ -5,3 +5,16 @@ /// <reference types="node" />

export declare function readUInt64LE(buffer: Buffer, offset: number): number;
/**
* Writes a 64-bit unsigned integer in little-endian format to the specified buffer at the given offset.
*
* @param buffer - The buffer to write the value to.
* @param value - The 64-bit unsigned integer value to write.
* @param offset - The offset in the buffer where the value should be written.
* @returns The new offset after writing the value.
*/
export declare function writeUInt64LE(buffer: Buffer, value: number, offset: number): number;
/**
* Reverses the order of bytes in a buffer.
* @param buffer - The buffer to reverse.
* @returns A new buffer with the bytes reversed.
*/
export declare function reverseBuffer(buffer: Buffer): Buffer;

@@ -8,0 +21,0 @@ export declare function cloneBuffer(buffer: Buffer): Buffer;

@@ -33,2 +33,10 @@ 'use strict';

exports.readUInt64LE = readUInt64LE;
/**
* Writes a 64-bit unsigned integer in little-endian format to the specified buffer at the given offset.
*
* @param buffer - The buffer to write the value to.
* @param value - The 64-bit unsigned integer value to write.
* @param offset - The offset in the buffer where the value should be written.
* @returns The new offset after writing the value.
*/
function writeUInt64LE(buffer, value, offset) {

@@ -41,2 +49,7 @@ verifuint(value, 0x001fffffffffffff);

exports.writeUInt64LE = writeUInt64LE;
/**
* Reverses the order of bytes in a buffer.
* @param buffer - The buffer to reverse.
* @returns A new buffer with the bytes reversed.
*/
function reverseBuffer(buffer) {

@@ -43,0 +56,0 @@ if (buffer.length < 1) return buffer;

@@ -13,4 +13,7 @@ /// <reference types="node" />

/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
/**
* Defines the tagged hash prefixes used in the crypto module.
*/
export declare const TAGGED_HASH_PREFIXES: TaggedHashPrefixes;
export declare function taggedHash(prefix: TaggedHashPrefix, data: Buffer): Buffer;
export {};

@@ -12,2 +12,8 @@ 'use strict';

void 0;
/**
* A module for hashing functions.
* include ripemd160、sha1、sha256、hash160、hash256、taggedHash
*
* @packageDocumentation
*/
const ripemd160_1 = require('@noble/hashes/ripemd160');

@@ -52,2 +58,5 @@ const sha1_1 = require('@noble/hashes/sha1');

/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
/**
* Defines the tagged hash prefixes used in the crypto module.
*/
exports.TAGGED_HASH_PREFIXES = {

@@ -54,0 +63,0 @@ 'BIP0340/challenge': Buffer.from([

import { TinySecp256k1Interface } from './types';
import * as bitcoinerlabEcc from '@exodus/bitcoinerlab-secp256k1';
export declare const eccLib: typeof bitcoinerlabEcc;
/**
* Initializes the ECC library with the provided instance.
* If `eccLib` is `undefined`, the library will be cleared.
* If `eccLib` is a new instance, it will be verified before setting it as the active library.
*
* @param eccLib The instance of the ECC library to initialize.
*/
export declare function initEccLib(eccLib: TinySecp256k1Interface | undefined): void;
/**
* Retrieves the ECC Library instance.
* Throws an error if the ECC Library is not provided.
* You must call initEccLib() with a valid TinySecp256k1Interface instance before calling this function.
* @returns The ECC Library instance.
* @throws Error if the ECC Library is not provided.
*/
export declare function getEccLib(): TinySecp256k1Interface;

@@ -11,2 +11,9 @@ 'use strict';

exports.eccLib = bitcoinerlabEcc;
/**
* Initializes the ECC library with the provided instance.
* If `eccLib` is `undefined`, the library will be cleared.
* If `eccLib` is a new instance, it will be verified before setting it as the active library.
*
* @param eccLib The instance of the ECC library to initialize.
*/
function initEccLib(eccLib) {

@@ -28,2 +35,9 @@ // Exodus change!

exports.initEccLib = initEccLib;
/**
* Retrieves the ECC Library instance.
* Throws an error if the ECC Library is not provided.
* You must call initEccLib() with a valid TinySecp256k1Interface instance before calling this function.
* @returns The ECC Library instance.
* @throws Error if the ECC Library is not provided.
*/
function getEccLib() {

@@ -38,2 +52,7 @@ if (!_ECCLIB_CACHE.eccLib)

const h = hex => Buffer.from(hex, 'hex');
/**
* Verifies the ECC functionality.
*
* @param ecc - The TinySecp256k1Interface object.
*/
function verifyEcc(ecc) {

@@ -40,0 +59,0 @@ assert(typeof ecc.isXOnlyPoint === 'function');

@@ -8,9 +8,13 @@ import * as address from './address';

export { Block } from './block';
/** @hidden */
export { TaggedHashPrefix } from './crypto';
export { Psbt, PsbtTxInput, PsbtTxOutput, Signer, SignerAsync, HDSigner, HDSignerAsync, } from './psbt';
/** @hidden */
export { OPS as opcodes } from './ops';
export { Transaction } from './transaction';
/** @hidden */
export { Network } from './networks';
/** @hidden */
export { Payment, PaymentCreator, PaymentOpts, Stack, StackElement, } from './payments';
export { Input as TxInput, Output as TxOutput } from './transaction';
export { initEccLib, eccLib } from './ecc_lib';

@@ -39,2 +39,3 @@ 'use strict';

});
/** @hidden */
var ops_1 = require('./ops');

@@ -41,0 +42,0 @@ Object.defineProperty(exports, 'opcodes', {

/// <reference types="node" />
/**
* Calculates the Merkle root of an array of buffers using a specified digest function.
*
* @param values - The array of buffers.
* @param digestFn - The digest function used to calculate the hash of the concatenated buffers.
* @returns The Merkle root as a buffer.
* @throws {TypeError} If the values parameter is not an array or the digestFn parameter is not a function.
*/
export declare function fastMerkleRoot(values: Buffer[], digestFn: (b: Buffer) => Buffer): Buffer;
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.fastMerkleRoot = void 0;
/**
* Calculates the Merkle root of an array of buffers using a specified digest function.
*
* @param values - The array of buffers.
* @param digestFn - The digest function used to calculate the hash of the concatenated buffers.
* @returns The Merkle root as a buffer.
* @throws {TypeError} If the values parameter is not an array or the digestFn parameter is not a function.
*/
function fastMerkleRoot(values, digestFn) {

@@ -5,0 +13,0 @@ if (!Array.isArray(values)) throw TypeError('Expected values Array');

@@ -0,1 +1,6 @@

/**
* Represents a Bitcoin network configuration,including messagePrefix, bech32, bip32, pubKeyHash, scriptHash, wif.
* Support bitcoin、bitcoin testnet and bitcoin regtest.
* @packageDocumentation
*/
export interface Network {

@@ -13,5 +18,14 @@ messagePrefix: string;

}
/**
* Represents the Bitcoin network configuration.
*/
export declare const bitcoin: Network;
/**
* Represents the regtest network configuration.
*/
export declare const regtest: Network;
/**
* Represents the testnet network configuration.
*/
export declare const testnet: Network;
export {};
'use strict';
// https://en.bitcoin.it/wiki/List_of_address_prefixes
// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
Object.defineProperty(exports, '__esModule', { value: true });
exports.testnet = exports.regtest = exports.bitcoin = void 0;
/**
* Represents the Bitcoin network configuration.
*/
exports.bitcoin = {
/**
* The message prefix used for signing Bitcoin messages.
*/
messagePrefix: '\x18Bitcoin Signed Message:\n',
/**
* The Bech32 prefix used for Bitcoin addresses.
*/
bech32: 'bc',
/**
* The BIP32 key prefixes for Bitcoin.
*/
bip32: {
/**
* The public key prefix for BIP32 extended public keys.
*/
public: 0x0488b21e,
/**
* The private key prefix for BIP32 extended private keys.
*/
private: 0x0488ade4,
},
/**
* The prefix for Bitcoin public key hashes.
*/
pubKeyHash: 0x00,
/**
* The prefix for Bitcoin script hashes.
*/
scriptHash: 0x05,
/**
* The prefix for Bitcoin Wallet Import Format (WIF) private keys.
*/
wif: 0x80,
};
/**
* Represents the regtest network configuration.
*/
exports.regtest = {

@@ -26,2 +58,5 @@ messagePrefix: '\x18Bitcoin Signed Message:\n',

};
/**
* Represents the testnet network configuration.
*/
exports.testnet = {

@@ -28,0 +63,0 @@ messagePrefix: '\x18Bitcoin Signed Message:\n',

@@ -24,2 +24,9 @@ /// <reference types="node" />

export type HashTree = HashLeaf | HashBranch;
/**
* Calculates the root hash from a given control block and leaf hash.
* @param controlBlock - The control block buffer.
* @param leafHash - The leaf hash buffer.
* @returns The root hash buffer.
* @throws {TypeError} If the control block length is less than 33.
*/
export declare function rootHashFromPath(controlBlock: Buffer, leafHash: Buffer): Buffer;

@@ -40,5 +47,25 @@ /**

export declare function findScriptPath(node: HashTree, hash: Buffer): Buffer[] | undefined;
/**
* Calculates the tapleaf hash for a given Tapleaf object.
* @param leaf - The Tapleaf object to calculate the hash for.
* @returns The tapleaf hash as a Buffer.
*/
export declare function tapleafHash(leaf: Tapleaf): Buffer;
/**
* Computes the taproot tweak hash for a given public key and optional hash.
* If a hash is provided, the public key and hash are concatenated before computing the hash.
* If no hash is provided, only the public key is used to compute the hash.
*
* @param pubKey - The public key buffer.
* @param h - The optional hash buffer.
* @returns The taproot tweak hash.
*/
export declare function tapTweakHash(pubKey: Buffer, h: Buffer | undefined): Buffer;
/**
* Tweak a public key with a given tweak hash.
* @param pubKey - The public key to be tweaked.
* @param h - The tweak hash.
* @returns The tweaked public key or null if the input is invalid.
*/
export declare function tweakKey(pubKey: Buffer, h: Buffer | undefined): TweakedPublicKey | null;
export {};

@@ -20,2 +20,9 @@ 'use strict';

const isHashBranch = ht => 'left' in ht && 'right' in ht;
/**
* Calculates the root hash from a given control block and leaf hash.
* @param controlBlock - The control block buffer.
* @param leafHash - The leaf hash buffer.
* @returns The root hash buffer.
* @throws {TypeError} If the control block length is less than 33.
*/
function rootHashFromPath(controlBlock, leafHash) {

@@ -76,2 +83,7 @@ if (controlBlock.length < 33)

exports.findScriptPath = findScriptPath;
/**
* Calculates the tapleaf hash for a given Tapleaf object.
* @param leaf - The Tapleaf object to calculate the hash for.
* @returns The tapleaf hash as a Buffer.
*/
function tapleafHash(leaf) {

@@ -88,2 +100,11 @@ const version = leaf.version || exports.LEAF_VERSION_TAPSCRIPT;

exports.tapleafHash = tapleafHash;
/**
* Computes the taproot tweak hash for a given public key and optional hash.
* If a hash is provided, the public key and hash are concatenated before computing the hash.
* If no hash is provided, only the public key is used to compute the hash.
*
* @param pubKey - The public key buffer.
* @param h - The optional hash buffer.
* @returns The taproot tweak hash.
*/
function tapTweakHash(pubKey, h) {

@@ -96,2 +117,8 @@ return bcrypto.taggedHash(

exports.tapTweakHash = tapTweakHash;
/**
* Tweak a public key with a given tweak hash.
* @param pubKey - The public key to be tweaked.
* @param h - The tweak hash.
* @returns The tweaked public key or null if the input is invalid.
*/
function tweakKey(pubKey, h) {

@@ -110,5 +137,18 @@ if (!buffer_1.Buffer.isBuffer(pubKey)) return null;

exports.tweakKey = tweakKey;
/**
* Computes the TapBranch hash by concatenating two buffers and applying the 'TapBranch' tagged hash algorithm.
*
* @param a - The first buffer.
* @param b - The second buffer.
* @returns The TapBranch hash of the concatenated buffers.
*/
function tapBranchHash(a, b) {
return bcrypto.taggedHash('TapBranch', buffer_1.Buffer.concat([a, b]));
}
/**
* Serializes a script by encoding its length as a varint and concatenating it with the script.
*
* @param s - The script to be serialized.
* @returns The serialized script as a Buffer.
*/
function serializeScript(s) {

@@ -115,0 +155,0 @@ const varintLen = bufferutils_1.varuint.encodingLength(s.length);

import { Payment, PaymentOpts } from './index';
/**
* Embeds data in a Bitcoin payment.
* @param a - The payment object.
* @param opts - Optional payment options.
* @returns The modified payment object.
* @throws {TypeError} If there is not enough data or if the output is invalid.
*/
export declare function p2data(a: Payment, opts?: PaymentOpts): Payment;

@@ -9,9 +9,10 @@ 'use strict';

const OPS = bscript.OPS;
function stacksEqual(a, b) {
if (a.length !== b.length) return false;
return a.every((x, i) => {
return x.equals(b[i]);
});
}
// output: OP_RETURN ...
/**
* Embeds data in a Bitcoin payment.
* @param a - The payment object.
* @param opts - Optional payment options.
* @returns The modified payment object.
* @throws {TypeError} If there is not enough data or if the output is invalid.
*/
function p2data(a, opts) {

@@ -47,3 +48,3 @@ if (!a.data && !a.output) throw new TypeError('Not enough data');

throw new TypeError('Output is invalid');
if (a.data && !stacksEqual(a.data, o.data))
if (a.data && !(0, types_1.stacksEqual)(a.data, o.data))
throw new TypeError('Data mismatch');

@@ -50,0 +51,0 @@ }

/// <reference types="node" />
/**
* Represents a payment object, which is used to create a payment.
*
* Supports P2PKH、P2SH、P2WPKH、P2WSH、P2TR and so on
*
* @packageDocumentation
*/
import { Network } from '../networks';

@@ -3,0 +10,0 @@ import { Taptree } from '../types';

import { Payment, PaymentOpts } from './index';
/**
* Represents a function that creates a Pay-to-Multisig (P2MS) payment object.
* @param a - The payment object.
* @param opts - Optional payment options.
* @returns The created payment object.
* @throws {TypeError} If the provided data is not valid.
*/
export declare function p2ms(a: Payment, opts?: PaymentOpts): Payment;

@@ -10,10 +10,11 @@ 'use strict';

const OP_INT_BASE = OPS.OP_RESERVED; // OP_1 - 1
function stacksEqual(a, b) {
if (a.length !== b.length) return false;
return a.every((x, i) => {
return x.equals(b[i]);
});
}
// input: OP_0 [signatures ...]
// output: m [pubKeys ...] n OP_CHECKMULTISIG
/**
* Represents a function that creates a Pay-to-Multisig (P2MS) payment object.
* @param a - The payment object.
* @param opts - Optional payment options.
* @returns The created payment object.
* @throws {TypeError} If the provided data is not valid.
*/
function p2ms(a, opts) {

@@ -121,3 +122,3 @@ if (

if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch');
if (a.pubkeys && !stacksEqual(a.pubkeys, o.pubkeys))
if (a.pubkeys && !(0, types_1.stacksEqual)(a.pubkeys, o.pubkeys))
throw new TypeError('Pubkeys mismatch');

@@ -144,3 +145,3 @@ }

throw new TypeError('Input has invalid signature(s)');
if (a.signatures && !stacksEqual(a.signatures, o.signatures))
if (a.signatures && !(0, types_1.stacksEqual)(a.signatures, o.signatures))
throw new TypeError('Signature mismatch');

@@ -147,0 +148,0 @@ if (a.m !== undefined && a.m !== a.signatures.length)

import { Payment, PaymentOpts } from './index';
/**
* Creates a pay-to-public-key (P2PK) payment object.
*
* @param a - The payment object containing the necessary data.
* @param opts - Optional payment options.
* @returns The P2PK payment object.
* @throws {TypeError} If the required data is not provided or if the data is invalid.
*/
export declare function p2pk(a: Payment, opts?: PaymentOpts): Payment;

@@ -11,2 +11,10 @@ 'use strict';

// output: {pubKey} OP_CHECKSIG
/**
* Creates a pay-to-public-key (P2PK) payment object.
*
* @param a - The payment object containing the necessary data.
* @param opts - Optional payment options.
* @returns The P2PK payment object.
* @throws {TypeError} If the required data is not provided or if the data is invalid.
*/
function p2pk(a, opts) {

@@ -13,0 +21,0 @@ if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature)

import { Payment, PaymentOpts } from './index';
/**
* Creates a Pay-to-Public-Key-Hash (P2PKH) payment object.
*
* @param a - The payment object containing the necessary data.
* @param opts - Optional payment options.
* @returns The P2PKH payment object.
* @throws {TypeError} If the required data is not provided or if the data is invalid.
*/
export declare function p2pkh(a: Payment, opts?: PaymentOpts): Payment;

@@ -13,2 +13,10 @@ 'use strict';

// output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG
/**
* Creates a Pay-to-Public-Key-Hash (P2PKH) payment object.
*
* @param a - The payment object containing the necessary data.
* @param opts - Optional payment options.
* @returns The P2PKH payment object.
* @throws {TypeError} If the required data is not provided or if the data is invalid.
*/
function p2pkh(a, opts) {

@@ -15,0 +23,0 @@ if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input)

import { Payment, PaymentOpts } from './index';
/**
* Creates a Pay-to-Script-Hash (P2SH) payment object.
*
* @param a - The payment object containing the necessary data.
* @param opts - Optional payment options.
* @returns The P2SH payment object.
* @throws {TypeError} If the required data is not provided or if the data is invalid.
*/
export declare function p2sh(a: Payment, opts?: PaymentOpts): Payment;

@@ -11,11 +11,13 @@ 'use strict';

const OPS = bscript.OPS;
function stacksEqual(a, b) {
if (a.length !== b.length) return false;
return a.every((x, i) => {
return x.equals(b[i]);
});
}
// input: [redeemScriptSig ...] {redeemScript}
// witness: <?>
// output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL
/**
* Creates a Pay-to-Script-Hash (P2SH) payment object.
*
* @param a - The payment object containing the necessary data.
* @param opts - Optional payment options.
* @returns The P2SH payment object.
* @throws {TypeError} If the required data is not provided or if the data is invalid.
*/
function p2sh(a, opts) {

@@ -192,3 +194,3 @@ if (!a.address && !a.hash && !a.output && !a.redeem && !a.input)

a.redeem.witness &&
!stacksEqual(a.redeem.witness, a.witness)
!(0, types_1.stacksEqual)(a.redeem.witness, a.witness)
)

@@ -195,0 +197,0 @@ throw new TypeError('Witness and redeem.witness mismatch');

import { Payment, PaymentOpts } from './index';
/**
* Creates a Pay-to-Taproot (P2TR) payment object.
*
* @param a - The payment object containing the necessary data for P2TR.
* @param opts - Optional payment options.
* @returns The P2TR payment object.
* @throws {TypeError} If the provided data is invalid or insufficient.
*/
export declare function p2tr(a: Payment, opts?: PaymentOpts): Payment;

@@ -12,5 +12,14 @@ 'use strict';

const bech32_1 = require('bech32');
const address_1 = require('../address');
const OPS = bscript.OPS;
const TAPROOT_WITNESS_VERSION = 0x01;
const ANNEX_PREFIX = 0x50;
/**
* Creates a Pay-to-Taproot (P2TR) payment object.
*
* @param a - The payment object containing the necessary data for P2TR.
* @param opts - Optional payment options.
* @returns The P2TR payment object.
* @throws {TypeError} If the provided data is invalid or insufficient.
*/
function p2tr(a, opts) {

@@ -57,10 +66,3 @@ if (

const _address = lazy.value(() => {
const result = bech32_1.bech32m.decode(a.address);
const version = result.words.shift();
const data = bech32_1.bech32m.fromWords(result.words);
return {
version,
prefix: result.prefix,
data: buffer_1.Buffer.from(data),
};
return (0, address_1.fromBech32)(a.address);
});

@@ -242,3 +244,3 @@ // remove annex if present, ignored by taproot

o.redeem.witness &&
!stacksEqual(a.redeem.witness, o.redeem.witness)
!(0, types_1.stacksEqual)(a.redeem.witness, o.redeem.witness)
)

@@ -295,7 +297,1 @@ throw new TypeError('Redeem.witness and witness mismatch');

exports.p2tr = p2tr;
function stacksEqual(a, b) {
if (a.length !== b.length) return false;
return a.every((x, i) => {
return x.equals(b[i]);
});
}
import { Payment, PaymentOpts } from './index';
/**
* Creates a pay-to-witness-public-key-hash (p2wpkh) payment object.
*
* @param a - The payment object containing the necessary data.
* @param opts - Optional payment options.
* @returns The p2wpkh payment object.
* @throws {TypeError} If the required data is missing or invalid.
*/
export declare function p2wpkh(a: Payment, opts?: PaymentOpts): Payment;

@@ -15,2 +15,10 @@ 'use strict';

// output: OP_0 {pubKeyHash}
/**
* Creates a pay-to-witness-public-key-hash (p2wpkh) payment object.
*
* @param a - The payment object containing the necessary data.
* @param opts - Optional payment options.
* @returns The p2wpkh payment object.
* @throws {TypeError} If the required data is missing or invalid.
*/
function p2wpkh(a, opts) {

@@ -17,0 +25,0 @@ if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness)

import { Payment, PaymentOpts } from './index';
/**
* Creates a Pay-to-Witness-Script-Hash (P2WSH) payment object.
*
* @param a - The payment object containing the necessary data.
* @param opts - Optional payment options.
* @returns The P2WSH payment object.
* @throws {TypeError} If the required data is missing or invalid.
*/
export declare function p2wsh(a: Payment, opts?: PaymentOpts): Payment;

@@ -12,8 +12,2 @@ 'use strict';

const EMPTY_BUFFER = Buffer.alloc(0);
function stacksEqual(a, b) {
if (a.length !== b.length) return false;
return a.every((x, i) => {
return x.equals(b[i]);
});
}
function chunkHasUncompressedPubkey(chunk) {

@@ -34,2 +28,10 @@ if (

// output: OP_0 {sha256(redeemScript)}
/**
* Creates a Pay-to-Witness-Script-Hash (P2WSH) payment object.
*
* @param a - The payment object containing the necessary data.
* @param opts - Optional payment options.
* @returns The P2WSH payment object.
* @throws {TypeError} If the required data is missing or invalid.
*/
function p2wsh(a, opts) {

@@ -195,3 +197,3 @@ if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness)

a.redeem.witness &&
!stacksEqual(a.witness, a.redeem.witness)
!(0, types_1.stacksEqual)(a.witness, a.redeem.witness)
)

@@ -198,0 +200,0 @@ throw new TypeError('Witness and redeem.witness mismatch');

@@ -27,2 +27,3 @@ /// <reference types="node" />

* Creator: This can be done with `new Psbt()`
*
* Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`,

@@ -38,2 +39,3 @@ * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to

* Also, check the integration tests for some examples of usage.
*
* Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input

@@ -44,2 +46,3 @@ * information for your pubkey or pubkeyhash, and only sign inputs where it finds

* and use something like a hardware wallet to sign with. (You must implement this)
*
* Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)`

@@ -49,2 +52,3 @@ * the psbt calling combine will always have precedence when a conflict occurs.

* all sequences, version, locktime, etc. are the same before combining.
*
* Input Finalizer: This role is fairly important. Not only does it need to construct

@@ -55,2 +59,3 @@ * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc.

* needed due to the finalized scripts containing the information.
*
* Transaction Extractor: This role will perform some checks before returning a

@@ -57,0 +62,0 @@ * Transaction object. Such as fee rate not being larger than maximumFeeRate etc.

@@ -37,2 +37,3 @@ 'use strict';

* Creator: This can be done with `new Psbt()`
*
* Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`,

@@ -48,2 +49,3 @@ * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to

* Also, check the integration tests for some examples of usage.
*
* Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input

@@ -54,2 +56,3 @@ * information for your pubkey or pubkeyhash, and only sign inputs where it finds

* and use something like a hardware wallet to sign with. (You must implement this)
*
* Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)`

@@ -59,2 +62,3 @@ * the psbt calling combine will always have precedence when a conflict occurs.

* all sequences, version, locktime, etc. are the same before combining.
*
* Input Finalizer: This role is fairly important. Not only does it need to construct

@@ -65,2 +69,3 @@ * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc.

* needed due to the finalized scripts containing the information.
*
* Transaction Extractor: This role will perform some checks before returning a

@@ -93,3 +98,3 @@ * Transaction object. Such as fee rate not being larger than maximumFeeRate etc.

__TX: this.data.globalMap.unsignedTx.tx,
// Psbt's predecesor (TransactionBuilder - now removed) behavior
// Psbt's predecessor (TransactionBuilder - now removed) behavior
// was to not confirm input values before signing.

@@ -247,3 +252,3 @@ // Even though we highly encourage people to get

const script = (0, address_1.toOutputScript)(address, network);
outputData = Object.assign(outputData, { script });
outputData = Object.assign({}, outputData, { script });
}

@@ -1272,3 +1277,3 @@ (0, bip371_1.checkTaprootOutputFields)(outputData, outputData, 'addOutput');

'means there is a chance that a miner could feed you incorrect information ' +
"to trick you into paying large fees. This behavior is the same as Psbt's predecesor " +
"to trick you into paying large fees. This behavior is the same as Psbt's predecessor " +
'(TransactionBuilder - now removed) when signing non-segwit scripts. You are not ' +

@@ -1364,3 +1369,3 @@ 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' +

values,
transaction_1.Transaction.SIGHASH_DEFAULT,
sighashType,
tapLeaf.hash,

@@ -1367,0 +1372,0 @@ );

/// <reference types="node" />
import { Taptree } from '../types';
import { PsbtInput, PsbtOutput, TapLeaf } from 'bip174/src/lib/interfaces';
/**
* Converts a public key to an X-only public key.
* @param pubKey The public key to convert.
* @returns The X-only public key.
*/
export declare const toXOnly: (pubKey: Buffer) => Buffer;

@@ -17,7 +22,45 @@ /**

};
/**
* Serializes a taproot signature.
* @param sig The signature to serialize.
* @param sighashType The sighash type. Optional.
* @returns The serialized taproot signature.
*/
export declare function serializeTaprootSignature(sig: Buffer, sighashType?: number): Buffer;
/**
* Checks if a PSBT input is a taproot input.
* @param input The PSBT input to check.
* @returns True if the input is a taproot input, false otherwise.
*/
export declare function isTaprootInput(input: PsbtInput): boolean;
/**
* Checks if a PSBT output is a taproot output.
* @param output The PSBT output to check.
* @param script The script to check. Optional.
* @returns True if the output is a taproot output, false otherwise.
*/
export declare function isTaprootOutput(output: PsbtOutput, script?: Buffer): boolean;
/**
* Checks the taproot input fields for consistency.
* @param inputData The original input data.
* @param newInputData The new input data.
* @param action The action being performed.
* @throws Throws an error if the input fields are inconsistent.
*/
export declare function checkTaprootInputFields(inputData: PsbtInput, newInputData: PsbtInput, action: string): void;
/**
* Checks the taproot output fields for consistency.
* @param outputData The original output data.
* @param newOutputData The new output data.
* @param action The action being performed.
* @throws Throws an error if the output fields are inconsistent.
*/
export declare function checkTaprootOutputFields(outputData: PsbtOutput, newOutputData: PsbtOutput, action: string): void;
/**
* Tweak the internal public key for a specific input.
* @param inputIndex - The index of the input.
* @param input - The PsbtInput object representing the input.
* @returns The tweaked internal public key.
* @throws Error if the tap internal key cannot be tweaked.
*/
export declare function tweakInternalPubKey(inputIndex: number, input: PsbtInput): Buffer;

@@ -42,2 +85,8 @@ /**

export declare function tapTreeFromList(leaves?: TapLeaf[]): Taptree;
/**
* Checks the taproot input for signatures.
* @param input The PSBT input to check.
* @param action The action being performed.
* @returns True if the input has taproot signatures, false otherwise.
*/
export declare function checkTaprootInputForSigs(input: PsbtInput, action: string): boolean;

@@ -21,2 +21,7 @@ 'use strict';

const psbtutils_2 = require('./psbtutils');
/**
* Converts a public key to an X-only public key.
* @param pubKey The public key to convert.
* @returns The X-only public key.
*/
const toXOnly = pubKey => (pubKey.length === 32 ? pubKey : pubKey.slice(1, 33));

@@ -50,2 +55,8 @@ exports.toXOnly = toXOnly;

exports.tapScriptFinalizer = tapScriptFinalizer;
/**
* Serializes a taproot signature.
* @param sig The signature to serialize.
* @param sighashType The sighash type. Optional.
* @returns The serialized taproot signature.
*/
function serializeTaprootSignature(sig, sighashType) {

@@ -58,2 +69,7 @@ const sighashTypeByte = sighashType

exports.serializeTaprootSignature = serializeTaprootSignature;
/**
* Checks if a PSBT input is a taproot input.
* @param input The PSBT input to check.
* @returns True if the input is a taproot input, false otherwise.
*/
function isTaprootInput(input) {

@@ -72,2 +88,8 @@ return (

exports.isTaprootInput = isTaprootInput;
/**
* Checks if a PSBT output is a taproot output.
* @param output The PSBT output to check.
* @param script The script to check. Optional.
* @returns True if the output is a taproot output, false otherwise.
*/
function isTaprootOutput(output, script) {

@@ -85,2 +107,9 @@ return (

exports.isTaprootOutput = isTaprootOutput;
/**
* Checks the taproot input fields for consistency.
* @param inputData The original input data.
* @param newInputData The new input data.
* @param action The action being performed.
* @throws Throws an error if the input fields are inconsistent.
*/
function checkTaprootInputFields(inputData, newInputData, action) {

@@ -91,2 +120,9 @@ checkMixedTaprootAndNonTaprootInputFields(inputData, newInputData, action);

exports.checkTaprootInputFields = checkTaprootInputFields;
/**
* Checks the taproot output fields for consistency.
* @param outputData The original output data.
* @param newOutputData The new output data.
* @param action The action being performed.
* @throws Throws an error if the output fields are inconsistent.
*/
function checkTaprootOutputFields(outputData, newOutputData, action) {

@@ -106,5 +142,12 @@ checkMixedTaprootAndNonTaprootOutputFields(outputData, newOutputData, action);

if (scriptPubkey && !scriptPubkey.equals(script))
throw new Error('Error adding output. Script or address missmatch.');
throw new Error('Error adding output. Script or address mismatch.');
}
}
/**
* Returns the Taproot script public key.
*
* @param tapInternalKey - The Taproot internal key.
* @param tapTree - The Taproot tree (optional).
* @returns The Taproot script public key.
*/
function getTaprootScripPubkey(tapInternalKey, tapTree) {

@@ -118,2 +161,9 @@ const scriptTree = tapTree && tapTreeFromList(tapTree.leaves);

}
/**
* Tweak the internal public key for a specific input.
* @param inputIndex - The index of the input.
* @param input - The PsbtInput object representing the input.
* @returns The tweaked internal public key.
* @throws Error if the tap internal key cannot be tweaked.
*/
function tweakInternalPubKey(inputIndex, input) {

@@ -166,2 +216,8 @@ const tapInternalKey = input.tapInternalKey;

exports.tapTreeFromList = tapTreeFromList;
/**
* Checks the taproot input for signatures.
* @param input The PSBT input to check.
* @param action The action being performed.
* @returns True if the input has taproot signatures, false otherwise.
*/
function checkTaprootInputForSigs(input, action) {

@@ -174,2 +230,7 @@ const sigs = extractTaprootSigs(input);

exports.checkTaprootInputForSigs = checkTaprootInputForSigs;
/**
* Decodes a Schnorr signature.
* @param signature The signature to decode.
* @returns The decoded Schnorr signature.
*/
function decodeSchnorrSignature(signature) {

@@ -182,2 +243,7 @@ return {

}
/**
* Extracts taproot signatures from a PSBT input.
* @param input The PSBT input to extract signatures from.
* @returns An array of taproot signatures.
*/
function extractTaprootSigs(input) {

@@ -194,2 +260,7 @@ const sigs = [];

}
/**
* Gets the taproot signature from the witness.
* @param finalScriptWitness The final script witness.
* @returns The taproot signature, or undefined if not found.
*/
function getTapKeySigFromWithness(finalScriptWitness) {

@@ -201,2 +272,10 @@ if (!finalScriptWitness) return;

}
/**
* Converts a binary tree to a BIP371 type list.
* @param tree The binary tap tree.
* @param leaves A list of tapleaves. Optional.
* @param depth The current depth. Optional.
* @returns A list of BIP 371 tapleaves.
* @throws Throws an error if the taptree cannot be converted to a tapleaf list.
*/
function _tapTreeToList(tree, leaves = [], depth = 0) {

@@ -218,2 +297,8 @@ if (depth > bip341_1.MAX_TAPTREE_DEPTH)

}
/**
* Inserts the tapleaves into the taproot tree.
* @param leaves The tapleaves to insert.
* @returns The taproot tree.
* @throws Throws an error if there is no room left to insert a tapleaf in the tree.
*/
function instertLeavesInTree(leaves) {

@@ -227,2 +312,9 @@ let tree;

}
/**
* Inserts a tapleaf into the taproot tree.
* @param leaf The tapleaf to insert.
* @param tree The taproot tree.
* @param depth The current depth. Optional.
* @returns The updated taproot tree.
*/
function instertLeafInTree(leaf, tree, depth = 0) {

@@ -245,2 +337,9 @@ if (depth > bip341_1.MAX_TAPTREE_DEPTH)

}
/**
* Checks the input fields for mixed taproot and non-taproot fields.
* @param inputData The original input data.
* @param newInputData The new input data.
* @param action The action being performed.
* @throws Throws an error if the input fields are inconsistent.
*/
function checkMixedTaprootAndNonTaprootInputFields(

@@ -265,2 +364,9 @@ inputData,

}
/**
* Checks the output fields for mixed taproot and non-taproot fields.
* @param inputData The original output data.
* @param newInputData The new output data.
* @param action The action being performed.
* @throws Throws an error if the output fields are inconsistent.
*/
function checkMixedTaprootAndNonTaprootOutputFields(

@@ -285,2 +391,10 @@ inputData,

}
/**
* Checks if the tap leaf is part of the tap tree for the given input data.
* Throws an error if the tap leaf is not part of the tap tree.
* @param inputData - The original PsbtInput data.
* @param newInputData - The new PsbtInput data.
* @param action - The action being performed.
* @throws {Error} - If the tap leaf is not part of the tap tree.
*/
function checkIfTapLeafInTree(inputData, newInputData, action) {

@@ -308,2 +422,8 @@ if (newInputData.tapMerkleRoot) {

}
/**
* Checks if a TapLeafScript is present in a Merkle tree.
* @param tapLeaf The TapLeafScript to check.
* @param merkleRoot The Merkle root of the tree. If not provided, the function assumes the TapLeafScript is present.
* @returns A boolean indicating whether the TapLeafScript is present in the tree.
*/
function isTapLeafInTree(tapLeaf, merkleRoot) {

@@ -321,2 +441,9 @@ if (!merkleRoot) return true;

}
/**
* Sorts the signatures in the input's tapScriptSig array based on their position in the tapLeaf script.
*
* @param input - The PsbtInput object.
* @param tapLeaf - The TapLeafScript object.
* @returns An array of sorted signatures as Buffers.
*/
function sortSignatures(input, tapLeaf) {

@@ -333,2 +460,8 @@ const leafHash = (0, bip341_1.tapleafHash)({

}
/**
* Adds the position of a public key in a script to a TapScriptSig object.
* @param script The script in which to find the position of the public key.
* @param tss The TapScriptSig object to add the position to.
* @returns A TapScriptSigWitPosition object with the added position.
*/
function addPubkeyPositionInScript(script, tss) {

@@ -364,2 +497,10 @@ return Object.assign(

}
/**
* Determines whether a TapLeafScript can be finalized.
*
* @param leaf - The TapLeafScript to check.
* @param tapScriptSig - The array of TapScriptSig objects.
* @param hash - The optional hash to compare with the leaf hash.
* @returns A boolean indicating whether the TapLeafScript can be finalized.
*/
function canFinalizeLeaf(leaf, tapScriptSig, hash) {

@@ -376,2 +517,8 @@ const leafHash = (0, bip341_1.tapleafHash)({

}
/**
* Checks if the given PsbtInput or PsbtOutput has non-taproot fields.
* Non-taproot fields include redeemScript, witnessScript, and bip32Derivation.
* @param io The PsbtInput or PsbtOutput to check.
* @returns A boolean indicating whether the given input or output has non-taproot fields.
*/
function hasNonTaprootFields(io) {

@@ -378,0 +525,0 @@ return (

@@ -10,5 +10,29 @@ /// <reference types="node" />

export declare const isP2TR: (script: Buffer) => boolean;
/**
* Converts a witness stack to a script witness.
* @param witness The witness stack to convert.
* @returns The script witness as a Buffer.
*/
export declare function witnessStackToScriptWitness(witness: Buffer[]): Buffer;
/**
* Finds the position of a public key in a script.
* @param pubkey The public key to search for.
* @param script The script to search in.
* @returns The index of the public key in the script, or -1 if not found.
* @throws {Error} If there is an unknown script error.
*/
export declare function pubkeyPositionInScript(pubkey: Buffer, script: Buffer): number;
/**
* Checks if a public key is present in a script.
* @param pubkey The public key to check.
* @param script The script to search in.
* @returns A boolean indicating whether the public key is present in the script.
*/
export declare function pubkeyInScript(pubkey: Buffer, script: Buffer): boolean;
/**
* Checks if an input contains a signature for a specific action.
* @param input - The input to check.
* @param action - The action to check for.
* @returns A boolean indicating whether the input contains a signature for the specified action.
*/
export declare function checkInputForSig(input: PsbtInput, action: string): boolean;

@@ -19,3 +43,10 @@ type SignatureDecodeFunc = (buffer: Buffer) => {

};
/**
* Determines if a given action is allowed for a signature block.
* @param signature - The signature block.
* @param signatureDecodeFn - The function used to decode the signature.
* @param action - The action to be checked.
* @returns True if the action is allowed, false otherwise.
*/
export declare function signatureBlocksAction(signature: Buffer, signatureDecodeFn: SignatureDecodeFunc, action: string): boolean;
export {};

@@ -21,2 +21,7 @@ 'use strict';

const payments = require('../payments');
/**
* Checks if a given payment factory can generate a payment script from a given script.
* @param payment The payment factory to check.
* @returns A function that takes a script and returns a boolean indicating whether the payment factory can generate a payment script from the script.
*/
function isPaymentFactory(payment) {

@@ -39,2 +44,7 @@ return script => {

exports.isP2TR = isPaymentFactory(payments.p2tr);
/**
* Converts a witness stack to a script witness.
* @param witness The witness stack to convert.
* @returns The script witness as a Buffer.
*/
function witnessStackToScriptWitness(witness) {

@@ -63,2 +73,9 @@ let buffer = Buffer.allocUnsafe(0);

exports.witnessStackToScriptWitness = witnessStackToScriptWitness;
/**
* Finds the position of a public key in a script.
* @param pubkey The public key to search for.
* @param script The script to search in.
* @returns The index of the public key in the script, or -1 if not found.
* @throws {Error} If there is an unknown script error.
*/
function pubkeyPositionInScript(pubkey, script) {

@@ -79,2 +96,8 @@ const pubkeyHash = (0, crypto_1.hash160)(pubkey);

exports.pubkeyPositionInScript = pubkeyPositionInScript;
/**
* Checks if a public key is present in a script.
* @param pubkey The public key to check.
* @param script The script to search in.
* @returns A boolean indicating whether the public key is present in the script.
*/
function pubkeyInScript(pubkey, script) {

@@ -84,2 +107,8 @@ return pubkeyPositionInScript(pubkey, script) !== -1;

exports.pubkeyInScript = pubkeyInScript;
/**
* Checks if an input contains a signature for a specific action.
* @param input - The input to check.
* @param action - The action to check for.
* @returns A boolean indicating whether the input contains a signature for the specified action.
*/
function checkInputForSig(input, action) {

@@ -92,2 +121,9 @@ const pSigs = extractPartialSigs(input);

exports.checkInputForSig = checkInputForSig;
/**
* Determines if a given action is allowed for a signature block.
* @param signature - The signature block.
* @param signatureDecodeFn - The function used to decode the signature.
* @param action - The action to be checked.
* @returns True if the action is allowed, false otherwise.
*/
function signatureBlocksAction(signature, signatureDecodeFn, action) {

@@ -115,2 +151,12 @@ const { hashType } = signatureDecodeFn(signature);

exports.signatureBlocksAction = signatureBlocksAction;
/**
* Extracts the signatures from a PsbtInput object.
* If the input has partial signatures, it returns an array of the signatures.
* If the input does not have partial signatures, it checks if it has a finalScriptSig or finalScriptWitness.
* If it does, it extracts the signatures from the final scripts and returns them.
* If none of the above conditions are met, it returns an empty array.
*
* @param input - The PsbtInput object from which to extract the signatures.
* @returns An array of signatures extracted from the PsbtInput object.
*/
function extractPartialSigs(input) {

@@ -126,2 +172,10 @@ let pSigs = [];

}
/**
* Retrieves the partial signatures (Psigs) from the input's final scripts.
* Psigs are extracted from both the final scriptSig and final scriptWitness of the input.
* Only canonical script signatures are considered.
*
* @param input - The PsbtInput object representing the input.
* @returns An array of PartialSig objects containing the extracted Psigs.
*/
function getPsigsFromInputFinalScripts(input) {

@@ -128,0 +182,0 @@ const scriptItems = !input.finalScriptSig

/// <reference types="node" />
/**
* Calculates the encoding length of a number used for push data in Bitcoin transactions.
* @param i The number to calculate the encoding length for.
* @returns The encoding length of the number.
*/
export declare function encodingLength(i: number): number;
/**
* Encodes a number into a buffer using a variable-length encoding scheme.
* The encoded buffer is written starting at the specified offset.
* Returns the size of the encoded buffer.
*
* @param buffer - The buffer to write the encoded data into.
* @param num - The number to encode.
* @param offset - The offset at which to start writing the encoded buffer.
* @returns The size of the encoded buffer.
*/
export declare function encode(buffer: Buffer, num: number, offset: number): number;
/**
* Decodes a buffer and returns information about the opcode, number, and size.
* @param buffer - The buffer to decode.
* @param offset - The offset within the buffer to start decoding.
* @returns An object containing the opcode, number, and size, or null if decoding fails.
*/
export declare function decode(buffer: Buffer, offset: number): {

@@ -5,0 +26,0 @@ opcode: number;

@@ -5,2 +5,7 @@ 'use strict';

const ops_1 = require('./ops');
/**
* Calculates the encoding length of a number used for push data in Bitcoin transactions.
* @param i The number to calculate the encoding length for.
* @returns The encoding length of the number.
*/
function encodingLength(i) {

@@ -10,2 +15,12 @@ return i < ops_1.OPS.OP_PUSHDATA1 ? 1 : i <= 0xff ? 2 : i <= 0xffff ? 3 : 5;

exports.encodingLength = encodingLength;
/**
* Encodes a number into a buffer using a variable-length encoding scheme.
* The encoded buffer is written starting at the specified offset.
* Returns the size of the encoded buffer.
*
* @param buffer - The buffer to write the encoded data into.
* @param num - The number to encode.
* @param offset - The offset at which to start writing the encoded buffer.
* @returns The size of the encoded buffer.
*/
function encode(buffer, num, offset) {

@@ -32,2 +47,8 @@ const size = encodingLength(num);

exports.encode = encode;
/**
* Decodes a buffer and returns information about the opcode, number, and size.
* @param buffer - The buffer to decode.
* @param offset - The offset within the buffer to start decoding.
* @returns An object containing the opcode, number, and size, or null if decoding fails.
*/
function decode(buffer, offset) {

@@ -34,0 +55,0 @@ const opcode = buffer.readUInt8(offset);

/// <reference types="node" />
/**
* Decodes a script number from a buffer.
*
* @param buffer - The buffer containing the script number.
* @param maxLength - The maximum length of the script number. Defaults to 4.
* @param minimal - Whether the script number should be minimal. Defaults to true.
* @returns The decoded script number.
* @throws {TypeError} If the script number overflows the maximum length.
* @throws {Error} If the script number is not minimally encoded when minimal is true.
*/
export declare function decode(buffer: Buffer, maxLength?: number, minimal?: boolean): number;
/**
* Encodes a number into a Buffer using a specific format.
*
* @param _number - The number to encode.
* @returns The encoded number as a Buffer.
*/
export declare function encode(_number: number): Buffer;
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.encode = exports.decode = void 0;
/**
* Decodes a script number from a buffer.
*
* @param buffer - The buffer containing the script number.
* @param maxLength - The maximum length of the script number. Defaults to 4.
* @param minimal - Whether the script number should be minimal. Defaults to true.
* @returns The decoded script number.
* @throws {TypeError} If the script number overflows the maximum length.
* @throws {Error} If the script number is not minimally encoded when minimal is true.
*/
function decode(buffer, maxLength, minimal) {

@@ -46,2 +56,8 @@ maxLength = maxLength || 4;

}
/**
* Encodes a number into a Buffer using a specific format.
*
* @param _number - The number to encode.
* @returns The encoded number as a Buffer.
*/
function encode(_number) {

@@ -48,0 +64,0 @@ let value = Math.abs(_number);

@@ -6,4 +6,17 @@ /// <reference types="node" />

}
/**
* Decodes a buffer into a ScriptSignature object.
* @param buffer - The buffer to decode.
* @returns The decoded ScriptSignature object.
* @throws Error if the hashType is invalid.
*/
export declare function decode(buffer: Buffer): ScriptSignature;
/**
* Encodes a signature and hash type into a buffer.
* @param signature - The signature to encode.
* @param hashType - The hash type to encode.
* @returns The encoded buffer.
* @throws Error if the hashType is invalid.
*/
export declare function encode(signature: Buffer, hashType: number): Buffer;
export {};

@@ -5,5 +5,11 @@ 'use strict';

const bip66 = require('./bip66');
const script_1 = require('./script');
const types = require('./types');
const { typeforce } = types;
const ZERO = Buffer.alloc(1, 0);
/**
* Converts a buffer to a DER-encoded buffer.
* @param x - The buffer to be converted.
* @returns The DER-encoded buffer.
*/
function toDER(x) {

@@ -17,2 +23,9 @@ let i = 0;

}
/**
* Converts a DER-encoded signature to a buffer.
* If the first byte of the input buffer is 0x00, it is skipped.
* The resulting buffer is 32 bytes long, filled with zeros if necessary.
* @param x - The DER-encoded signature.
* @returns The converted buffer.
*/
function fromDER(x) {

@@ -26,7 +39,13 @@ if (x[0] === 0x00) x = x.slice(1);

// BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed)
/**
* Decodes a buffer into a ScriptSignature object.
* @param buffer - The buffer to decode.
* @returns The decoded ScriptSignature object.
* @throws Error if the hashType is invalid.
*/
function decode(buffer) {
const hashType = buffer.readUInt8(buffer.length - 1);
const hashTypeMod = hashType & ~0x80;
if (hashTypeMod <= 0 || hashTypeMod >= 4)
if (!(0, script_1.isDefinedHashType)(hashType)) {
throw new Error('Invalid hashType ' + hashType);
}
const decoded = bip66.decode(buffer.slice(0, -1));

@@ -39,2 +58,9 @@ const r = fromDER(decoded.r);

exports.decode = decode;
/**
* Encodes a signature and hash type into a buffer.
* @param signature - The signature to encode.
* @param hashType - The hash type to encode.
* @returns The encoded buffer.
* @throws Error if the hashType is invalid.
*/
function encode(signature, hashType) {

@@ -48,5 +74,5 @@ typeforce(

);
const hashTypeMod = hashType & ~0x80;
if (hashTypeMod <= 0 || hashTypeMod >= 4)
if (!(0, script_1.isDefinedHashType)(hashType)) {
throw new Error('Invalid hashType ' + hashType);
}
const hashTypeBuffer = Buffer.allocUnsafe(1);

@@ -53,0 +79,0 @@ hashTypeBuffer.writeUInt8(hashType, 0);

@@ -9,6 +9,30 @@ /// <reference types="node" />

export declare function countNonPushOnlyOPs(value: Stack): number;
/**
* Compiles an array of chunks into a Buffer.
*
* @param chunks - The array of chunks to compile.
* @returns The compiled Buffer.
* @throws Error if the compilation fails.
*/
export declare function compile(chunks: Buffer | Stack): Buffer;
export declare function decompile(buffer: Buffer | Array<number | Buffer>): Array<number | Buffer> | null;
/**
* Converts the given chunks into an ASM (Assembly) string representation.
* If the chunks parameter is a Buffer, it will be decompiled into a Stack before conversion.
* @param chunks - The chunks to convert into ASM.
* @returns The ASM string representation of the chunks.
*/
export declare function toASM(chunks: Buffer | Array<number | Buffer>): string;
/**
* Converts an ASM string to a Buffer.
* @param asm The ASM string to convert.
* @returns The converted Buffer.
*/
export declare function fromASM(asm: string): Buffer;
/**
* Converts the given chunks into a stack of buffers.
*
* @param chunks - The chunks to convert.
* @returns The stack of buffers.
*/
export declare function toStack(chunks: Buffer | Array<number | Buffer>): Buffer[];

@@ -15,0 +39,0 @@ export declare function isCanonicalPubKey(buffer: Buffer): boolean;

@@ -17,2 +17,6 @@ 'use strict';

void 0;
/**
* Script tools, including decompile, compile, toASM, fromASM, toStack, isCanonicalPubKey, isCanonicalScriptSignature
* @packageDocumentation
*/
const bip66 = require('./bip66');

@@ -66,2 +70,9 @@ const ops_1 = require('./ops');

}
/**
* Compiles an array of chunks into a Buffer.
*
* @param chunks - The array of chunks to compile.
* @returns The compiled Buffer.
* @throws Error if the compilation fails.
*/
function compile(chunks) {

@@ -142,2 +153,8 @@ // TODO: remove me

exports.decompile = decompile;
/**
* Converts the given chunks into an ASM (Assembly) string representation.
* If the chunks parameter is a Buffer, it will be decompiled into a Stack before conversion.
* @param chunks - The chunks to convert into ASM.
* @returns The ASM string representation of the chunks.
*/
function toASM(chunks) {

@@ -147,2 +164,5 @@ if (chunksIsBuffer(chunks)) {

}
if (!chunks) {
throw new Error('Could not convert invalid chunks to ASM');
}
return chunks

@@ -162,2 +182,7 @@ .map(chunk => {

exports.toASM = toASM;
/**
* Converts an ASM string to a Buffer.
* @param asm The ASM string to convert.
* @returns The converted Buffer.
*/
function fromASM(asm) {

@@ -176,2 +201,8 @@ typeforce(types.String, asm);

exports.fromASM = fromASM;
/**
* Converts the given chunks into a stack of buffers.
*
* @param chunks - The chunks to convert.
* @returns The stack of buffers.
*/
function toStack(chunks) {

@@ -178,0 +209,0 @@ chunks = decompile(chunks);

@@ -13,2 +13,5 @@ /// <reference types="node" />

}
/**
* Represents a Bitcoin transaction.
*/
export declare class Transaction {

@@ -15,0 +18,0 @@ static readonly DEFAULT_SEQUENCE = 4294967295;

@@ -41,2 +41,5 @@ 'use strict';

}
/**
* Represents a Bitcoin transaction.
*/
class Transaction {

@@ -319,2 +322,4 @@ constructor() {

if (!(isNone || isSingle)) {
if (!this.outs.length)
throw new Error('Add outputs to the transaction before signing.');
const txOutsSize = this.outs

@@ -321,0 +326,0 @@ .map(output => 8 + varSliceSize(output.script))

/// <reference types="node" />
export declare const typeforce: any;
/**
* Checks if two arrays of Buffers are equal.
* @param a - The first array of Buffers.
* @param b - The second array of Buffers.
* @returns True if the arrays are equal, false otherwise.
*/
export declare function stacksEqual(a: Buffer[], b: Buffer[]): boolean;
/**
* Checks if the given value is a valid elliptic curve point.
* @param p - The value to check.
* @returns True if the value is a valid elliptic curve point, false otherwise.
*/
export declare function isPoint(p: Buffer | number | undefined | null): boolean;
export declare function UInt31(value: number): boolean;
export declare function BIP32Path(value: string): boolean;
export declare namespace BIP32Path {
var toJSON: () => string;
}
export declare function Signer(obj: any): boolean;
export declare function Satoshi(value: number): boolean;
export declare const ECPoint: any;
export declare const Network: any;
export interface XOnlyPointAddTweakResult {

@@ -14,0 +18,0 @@ parity: 1 | 0;

@@ -23,9 +23,5 @@ 'use strict';

exports.TAPLEAF_VERSION_MASK =
exports.Network =
exports.ECPoint =
exports.Satoshi =
exports.Signer =
exports.BIP32Path =
exports.UInt31 =
exports.isPoint =
exports.stacksEqual =
exports.typeforce =

@@ -40,2 +36,20 @@ void 0;

);
/**
* Checks if two arrays of Buffers are equal.
* @param a - The first array of Buffers.
* @param b - The second array of Buffers.
* @returns True if the arrays are equal, false otherwise.
*/
function stacksEqual(a, b) {
if (a.length !== b.length) return false;
return a.every((x, i) => {
return x.equals(b[i]);
});
}
exports.stacksEqual = stacksEqual;
/**
* Checks if the given value is a valid elliptic curve point.
* @param p - The value to check.
* @returns True if the value is a valid elliptic curve point, false otherwise.
*/
function isPoint(p) {

@@ -58,24 +72,2 @@ if (!buffer_1.Buffer.isBuffer(p)) return false;

exports.isPoint = isPoint;
const UINT31_MAX = Math.pow(2, 31) - 1;
function UInt31(value) {
return exports.typeforce.UInt32(value) && value <= UINT31_MAX;
}
exports.UInt31 = UInt31;
function BIP32Path(value) {
return (
exports.typeforce.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/)
);
}
exports.BIP32Path = BIP32Path;
BIP32Path.toJSON = () => {
return 'BIP32 derivation path';
};
function Signer(obj) {
return (
(exports.typeforce.Buffer(obj.publicKey) ||
typeof obj.getPublicKey === 'function') &&
typeof obj.sign === 'function'
);
}
exports.Signer = Signer;
const SATOSHI_MAX = 21 * 1e14;

@@ -86,18 +78,2 @@ function Satoshi(value) {

exports.Satoshi = Satoshi;
// external dependent types
exports.ECPoint = exports.typeforce.quacksLike('Point');
// exposed, external API
exports.Network = exports.typeforce.compile({
messagePrefix: exports.typeforce.oneOf(
exports.typeforce.Buffer,
exports.typeforce.String,
),
bip32: {
public: exports.typeforce.UInt32,
private: exports.typeforce.UInt32,
},
pubKeyHash: exports.typeforce.UInt8,
scriptHash: exports.typeforce.UInt8,
wif: exports.typeforce.UInt8,
});
exports.TAPLEAF_VERSION_MASK = 0xfe;

@@ -104,0 +80,0 @@ function isTapleaf(o) {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc