ts-sdk

API

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables

Interfaces

Classes

     
BasePoint PointInFiniteField SHA256HMAC
BigNumber Polynomial SHA512
Curve PrivateKey SHA512HMAC
DRBG PublicKey Schnorr
JacobianPoint RIPEMD160 Signature
K256 Reader SymmetricKey
KeyShares ReductionContext TransactionSignature
Mersenne SHA1 Writer
MontgomoryMethod SHA1HMAC  
Point SHA256  

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: BasePoint

Base class for Point (affine coordinates) and JacobianPoint classes, defining their curve and type.

export default abstract class BasePoint {
    curve: Curve;
    type: "affine" | "jacobian";
    precomputed: {
        doubles?: {
            step: number;
            points: BasePoint[];
        };
        naf?: {
            wnd: number;
            points: BasePoint[];
        };
        beta?: BasePoint | null;
    } | null;
    constructor(type: "affine" | "jacobian") 
}

See also: Curve

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: BigNumber

JavaScript numbers are only precise up to 53 bits. Since Bitcoin relies on 256-bit cryptography, this BigNumber class enables operations on larger numbers.

export default class BigNumber {
    public static readonly zeros: string[] 
    static readonly groupSizes: number[] 
    static readonly groupBases: number[] 
    static readonly wordSize: number = 26;
    public red: ReductionContext | null;
    public get negative(): number 
    public set negative(val: number) 
    public get words(): number[] 
    public set words(newWords: number[]) 
    public get length(): number 
    static isBN(num: any): boolean 
    static max(left: BigNumber, right: BigNumber): BigNumber 
    static min(left: BigNumber, right: BigNumber): BigNumber 
    constructor(number: number | string | number[] | bigint | undefined = 0, base: number | "be" | "le" | "hex" = 10, endian: "be" | "le" = "be") 
    copy(dest: BigNumber): void 
    static move(dest: BigNumber, src: BigNumber): void 
    clone(): BigNumber 
    expand(size: number): this 
    strip(): this 
    normSign(): this { if (this._magnitude === 0n)
        this._sign = 0; return this; }
    inspect(): string 
    toString(base: number | "hex" = 10, padding: number = 1): string 
    toNumber(): number 
    toJSON(): string 
    toArray(endian: "le" | "be" = "be", length?: number): number[] 
    bitLength(): number { if (this._magnitude === 0n)
        return 0; return this._magnitude.toString(2).length; }
    static toBitArray(num: BigNumber): Array<0 | 1> 
    toBitArray(): Array<0 | 1> 
    zeroBits(): number 
    byteLength(): number { if (this._magnitude === 0n)
        return 0; return Math.ceil(this.bitLength() / 8); }
    toTwos(width: number): BigNumber { this.assert(width >= 0); const Bw = BigInt(width); let v = this._getSignedValue(); if (this._sign === 1 && this._magnitude !== 0n)
        v = (1n << Bw) + v; const m = (1n << Bw) - 1n; v &= m; const r = new BigNumber(0n); r._initializeState(v, 0); return r; }
    fromTwos(width: number): BigNumber 
    isNeg(): boolean 
    neg(): BigNumber 
    ineg(): this { if (this._magnitude !== 0n)
        this._sign = this._sign === 1 ? 0 : 1; return this; }
    iuor(num: BigNumber): this 
    iuand(num: BigNumber): this 
    iuxor(num: BigNumber): this 
    ior(num: BigNumber): this 
    iand(num: BigNumber): this 
    ixor(num: BigNumber): this 
    or(num: BigNumber): BigNumber 
    uor(num: BigNumber): BigNumber 
    and(num: BigNumber): BigNumber 
    uand(num: BigNumber): BigNumber 
    xor(num: BigNumber): BigNumber 
    uxor(num: BigNumber): BigNumber 
    inotn(width: number): this 
    notn(width: number): BigNumber 
    setn(bit: number, val: any): this { this.assert(typeof bit === "number" && bit >= 0); const Bb = BigInt(bit); if (val === 1 || val === true)
        this._magnitude |= (1n << Bb);
    else
        this._magnitude &= ~(1n << Bb); const wnb = Math.floor(bit / BigNumber.wordSize) + 1; this._nominalWordLength = Math.max(this._nominalWordLength, wnb); this._finishInitialization(); return this.strip(); }
    iadd(num: BigNumber): this 
    add(num: BigNumber): BigNumber 
    isub(num: BigNumber): this 
    sub(num: BigNumber): BigNumber 
    mul(num: BigNumber): BigNumber 
    imul(num: BigNumber): this 
    imuln(num: number): this 
    muln(num: number): BigNumber 
    sqr(): BigNumber 
    isqr(): this 
    pow(num: BigNumber): BigNumber 
    iushln(bits: number): this { this.assert(typeof bits === "number" && bits >= 0); if (bits === 0)
        return this; this._magnitude <<= BigInt(bits); this._finishInitialization(); return this.strip(); }
    ishln(bits: number): this 
    iushrn(bits: number, hint?: number, extended?: BigNumber): this { this.assert(typeof bits === "number" && bits >= 0); if (bits === 0) {
        if (extended != null)
            extended._initializeState(0n, 0);
        return this;
    } if (extended != null) {
        const m = (1n << BigInt(bits)) - 1n;
        const sOut = this._magnitude & m;
        extended._initializeState(sOut, 0);
    } this._magnitude >>= BigInt(bits); this._finishInitialization(); return this.strip(); }
    ishrn(bits: number, hint?: number, extended?: BigNumber): this 
    shln(bits: number): BigNumber 
    ushln(bits: number): BigNumber 
    shrn(bits: number): BigNumber 
    ushrn(bits: number): BigNumber 
    testn(bit: number): boolean 
    imaskn(bits: number): this 
    maskn(bits: number): BigNumber 
    iaddn(num: number): this 
    _iaddn(num: number): this 
    isubn(num: number): this 
    addn(num: number): BigNumber 
    subn(num: number): BigNumber 
    iabs(): this 
    abs(): BigNumber 
    divmod(num: BigNumber, mode?: "div" | "mod", positive?: boolean): any 
    div(num: BigNumber): BigNumber 
    mod(num: BigNumber): BigNumber 
    umod(num: BigNumber): BigNumber 
    divRound(num: BigNumber): BigNumber 
    modrn(numArg: number): number 
    idivn(num: number): this 
    divn(num: number): BigNumber 
    egcd(p: BigNumber): {
        a: BigNumber;
        b: BigNumber;
        gcd: BigNumber;
    } { this.assert(p._sign === 0, "p must not be negative"); this.assert(!p.isZero(), "p must not be zero"); let uV = this._getSignedValue(); let vV = p._magnitude; let a = 1n; let pa = 0n; let b = 0n; let pb = 1n; while (vV !== 0n) {
        const q = uV / vV;
        let t = vV;
        vV = uV % vV;
        uV = t;
        t = pa;
        pa = a - q * pa;
        a = t;
        t = pb;
        pb = b - q * pb;
        b = t;
    } const ra = new BigNumber(0n); ra._setValueFromSigned(a); const rb = new BigNumber(0n); rb._setValueFromSigned(b); const rg = new BigNumber(0n); rg._initializeState(uV < 0n ? -uV : uV, 0); return { a: ra, b: rb, gcd: rg }; }
    gcd(num: BigNumber): BigNumber { let u = this._magnitude; let v = num._magnitude; if (u === 0n) {
        const r = new BigNumber(0n);
        r._setValueFromSigned(v);
        return r.iabs();
    } if (v === 0n) {
        const r = new BigNumber(0n);
        r._setValueFromSigned(u);
        return r.iabs();
    } while (v !== 0n) {
        const t = u % v;
        u = v;
        v = t;
    } const res = new BigNumber(0n); res._initializeState(u, 0); return res; }
    invm(num: BigNumber): BigNumber 
    isEven(): boolean 
    isOdd(): boolean 
    andln(num: number): number 
    bincn(bit: number): this 
    isZero(): boolean 
    cmpn(num: number): 1 | 0 | -1 { this.assert(Math.abs(num) <= BigNumber.MAX_IMULN_ARG, "Number is too big"); const tV = this._getSignedValue(); const nV = BigInt(num); if (tV < nV)
        return -1; if (tV > nV)
        return 1; return 0; }
    cmp(num: BigNumber): 1 | 0 | -1 { const tV = this._getSignedValue(); const nV = num._getSignedValue(); if (tV < nV)
        return -1; if (tV > nV)
        return 1; return 0; }
    ucmp(num: BigNumber): 1 | 0 | -1 { if (this._magnitude < num._magnitude)
        return -1; if (this._magnitude > num._magnitude)
        return 1; return 0; }
    gtn(num: number): boolean 
    gt(num: BigNumber): boolean 
    gten(num: number): boolean 
    gte(num: BigNumber): boolean 
    ltn(num: number): boolean 
    lt(num: BigNumber): boolean 
    lten(num: number): boolean 
    lte(num: BigNumber): boolean 
    eqn(num: number): boolean 
    eq(num: BigNumber): boolean 
    toRed(ctx: ReductionContext): BigNumber 
    fromRed(): BigNumber 
    forceRed(ctx: ReductionContext): this 
    redAdd(num: BigNumber): BigNumber 
    redIAdd(num: BigNumber): BigNumber 
    redSub(num: BigNumber): BigNumber 
    redISub(num: BigNumber): BigNumber 
    redShl(num: number): BigNumber 
    redMul(num: BigNumber): BigNumber 
    redIMul(num: BigNumber): BigNumber 
    redSqr(): BigNumber 
    redISqr(): BigNumber 
    redSqrt(): BigNumber 
    redInvm(): BigNumber 
    redNeg(): BigNumber 
    redPow(num: BigNumber): BigNumber 
    static fromHex(hex: string, endian?: "le" | "be" | "little" | "big"): BigNumber 
    toHex(byteLength: number = 0): string 
    static fromJSON(str: string): BigNumber 
    static fromNumber(n: number): BigNumber 
    static fromString(str: string, base?: number | "hex"): BigNumber 
    static fromSm(bytes: number[], endian: "big" | "little" = "big"): BigNumber 
    toSm(endian: "big" | "little" = "big"): number[] 
    static fromBits(bits: number, strict: boolean = false): BigNumber 
    toBits(): number 
    static fromScriptNum(num: number[], requireMinimal: boolean = false, maxNumSize?: number): BigNumber 
    toScriptNum(): number[] 
    _invmp(p: BigNumber): BigNumber 
    mulTo(num: BigNumber, out: BigNumber): BigNumber 
}

See also: ReductionContext, toArray, toHex

Constructor

constructor(number: number | string | number[] | bigint | undefined = 0, base: number | "be" | "le" | "hex" = 10, endian: "be" | "le" = "be") 

Argument Details

Property red

Reduction context of the big number.

public red: ReductionContext | null

See also: ReductionContext

Property wordSize

The word size of big number chunks.

static readonly wordSize: number = 26

Example

console.log(BigNumber.wordSize);  // output: 26

Method _invmp

Compute the multiplicative inverse of the current BigNumber in the modulus field specified by p. The multiplicative inverse is a number which when multiplied with the current BigNumber gives ‘1’ in the modulus field.

_invmp(p: BigNumber): BigNumber 

See also: BigNumber

Returns

The multiplicative inverse BigNumber in the modulus field specified by p.

Argument Details

Method bitLength

Calculates the number of bits required to represent the BigNumber.

bitLength(): number { if (this._magnitude === 0n)
    return 0; return this._magnitude.toString(2).length; }

Returns

The bit length of the BigNumber.

Method byteLength

Calculates the number of bytes required to represent the BigNumber.

byteLength(): number { if (this._magnitude === 0n)
    return 0; return Math.ceil(this.bitLength() / 8); }

Returns

The byte length of the BigNumber.

Method fromBits

Creates a BigNumber from a number representing the “bits” value in a block header.

static fromBits(bits: number, strict: boolean = false): BigNumber 

See also: BigNumber

Returns

Returns a BigNumber equivalent to the “bits” value in a block header.

Argument Details

Throws

Will throw an error if strict is true and the number has negative bit set.

Method fromHex

Creates a BigNumber from a hexadecimal string.

static fromHex(hex: string, endian?: "le" | "be" | "little" | "big"): BigNumber 

See also: BigNumber

Returns

Returns a BigNumber created from the hexadecimal input string.

Argument Details

Example

const exampleHex = 'a1b2c3';
const bigNumber = BigNumber.fromHex(exampleHex);

Method fromJSON

Creates a BigNumber from a JSON-serialized string.

static fromJSON(str: string): BigNumber 

See also: BigNumber

Returns

Returns a BigNumber created from the JSON input string.

Argument Details

Method fromNumber

Creates a BigNumber from a number.

static fromNumber(n: number): BigNumber 

See also: BigNumber

Returns

Returns a BigNumber equivalent to the input number.

Argument Details

Method fromScriptNum

Creates a BigNumber from the format used in Bitcoin scripts.

static fromScriptNum(num: number[], requireMinimal: boolean = false, maxNumSize?: number): BigNumber 

See also: BigNumber

Returns

Returns a BigNumber equivalent to the number used in a Bitcoin script.

Argument Details

Method fromSm

Creates a BigNumber from a signed magnitude number.

static fromSm(bytes: number[], endian: "big" | "little" = "big"): BigNumber 

See also: BigNumber

Returns

Returns a BigNumber equivalent to the signed magnitude number interpreted with specified endianess.

Argument Details

Method fromString

Creates a BigNumber from a string, considering an optional base.

static fromString(str: string, base?: number | "hex"): BigNumber 

See also: BigNumber

Returns

Returns a BigNumber equivalent to the string after conversion from the specified base.

Argument Details

Method isBN

Checks whether a value is an instance of BigNumber. Regular JS numbers fail this check.

static isBN(num: any): boolean 

Returns

Argument Details

Method max

Returns the bigger value between two BigNumbers

static max(left: BigNumber, right: BigNumber): BigNumber 

See also: BigNumber

Returns

Argument Details

Method min

Returns the smaller value between two BigNumbers

static min(left: BigNumber, right: BigNumber): BigNumber 

See also: BigNumber

Returns

Argument Details

Method mulTo

Performs multiplication between the BigNumber instance and a given BigNumber. It chooses the multiplication method based on the lengths of the numbers to optimize execution time.

mulTo(num: BigNumber, out: BigNumber): BigNumber 

See also: BigNumber

Returns

The BigNumber resulting from the multiplication operation.

Argument Details

Method toArray

Converts the BigNumber instance to an array of bytes.

toArray(endian: "le" | "be" = "be", length?: number): number[] 

Returns

Array of bytes representing the BigNumber.

Argument Details

Method toBitArray

Converts a BigNumber to an array of bits.

static toBitArray(num: BigNumber): Array<0 | 1> 

See also: BigNumber

Returns

An array of bits.

Argument Details

Method toBits

Converts this BigNumber to a number representing the “bits” value in a block header.

toBits(): number 

Returns

Returns a number equivalent to the “bits” value in a block header.

Method toHex

Converts this BigNumber to a hexadecimal string.

toHex(byteLength: number = 0): string 

Returns

Returns a string representing the hexadecimal value of this BigNumber.

Argument Details

Example

const bigNumber = new BigNumber(255)
const hex = bigNumber.toHex()

Method toJSON

Converts the BigNumber instance to a JSON-formatted string.

toJSON(): string 

Returns

The JSON string representation of the BigNumber instance.

Method toNumber

Converts the BigNumber instance to a JavaScript number. Please note that JavaScript numbers are only precise up to 53 bits.

toNumber(): number 

Returns

The JavaScript number representation of the BigNumber instance.

Throws

If the BigNumber instance cannot be safely stored in a JavaScript number

Method toScriptNum

Converts this BigNumber to a number in the format used in Bitcoin scripts.

toScriptNum(): number[] 

Returns

Returns the equivalent to this BigNumber as a Bitcoin script number.

Method toSm

Converts this BigNumber to a signed magnitude number.

toSm(endian: "big" | "little" = "big"): number[] 

Returns

Returns an array equivalent to this BigNumber interpreted as a signed magnitude with specified endianess.

Argument Details

Method toString

function toString() { [native code] }

Converts the BigNumber instance to a string representation.

toString(base: number | "hex" = 10, padding: number = 1): string 

Returns

The string representation of the BigNumber instance

Argument Details

Method zeroBits

Returns the number of trailing zero bits in the big number.

zeroBits(): number 

Returns

Returns the number of trailing zero bits in the binary representation of the big number.

Example

const bn = new BigNumber('8'); // binary: 1000
const zeroBits = bn.zeroBits(); // 3

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: Curve

export default class Curve {
    p: BigNumber;
    red: ReductionContext;
    redN: BigNumber | null;
    zero: BigNumber;
    one: BigNumber;
    two: BigNumber;
    g: Point;
    n: BigNumber;
    a: BigNumber;
    b: BigNumber;
    tinv: BigNumber;
    zeroA: boolean;
    threeA: boolean;
    endo: {
        beta: BigNumber;
        lambda: BigNumber;
        basis: Array<{
            a: BigNumber;
            b: BigNumber;
        }>;
    } | undefined;
    _endoWnafT1: BigNumber[];
    _endoWnafT2: BigNumber[];
    _wnafT1: BigNumber[];
    _wnafT2: BigNumber[];
    _wnafT3: BigNumber[];
    _wnafT4: BigNumber[];
    _bitLength: number;
    static assert(expression: unknown, message: string = "Elliptic curve assertion failed"): void 
    getNAF(num: BigNumber, w: number, bits: number): number[] 
    getJSF(k1: BigNumber, k2: BigNumber): number[][] 
    static cachedProperty(obj, name: string, computer): void 
    static parseBytes(bytes: string | number[]): number[] 
    static intFromLE(bytes: number[]): BigNumber 
    constructor() 
    _getEndomorphism(conf): {
        beta: BigNumber;
        lambda: BigNumber;
        basis: Array<{
            a: BigNumber;
            b: BigNumber;
        }>;
    } | undefined 
    _getEndoRoots(num: BigNumber): [
        BigNumber,
        BigNumber
    ] 
    _getEndoBasis(lambda: BigNumber): [
        {
            a: BigNumber;
            b: BigNumber;
        },
        {
            a: BigNumber;
            b: BigNumber;
        }
    ] 
    _endoSplit(k: BigNumber): {
        k1: BigNumber;
        k2: BigNumber;
    } 
    validate(point: Point): boolean 
}

See also: BigNumber, Point, ReductionContext

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: DRBG

This class behaves as a HMAC-based deterministic random bit generator (DRBG). It implements a deterministic random number generator using SHA256HMAC HASH function. It takes an initial entropy and nonce when instantiated for seeding purpose.

Example

const drbg = new DRBG('af12de...', '123ef...');
export default class DRBG {
    K: number[];
    V: number[];
    constructor(entropy: number[] | string, nonce: number[] | string) 
    hmac(): SHA256HMAC 
    update(seed?): void 
    generate(len: number): string 
}

See also: SHA256HMAC

Method generate

Generates deterministic random hexadecimal string of given length. In every generation process, it also updates the internal state K and V.

generate(len: number): string 

Returns

The required deterministic random hexadecimal string.

Argument Details

Example

const randomHex = drbg.generate(256);

Method hmac

Generates HMAC using the K value of the instance. This method is used internally for operations.

hmac(): SHA256HMAC 

See also: SHA256HMAC

Returns

The SHA256HMAC object created with K value.

Example

const hmac = drbg.hmac();

Method update

Updates the K and V values of the instance based on the seed. The seed if not provided uses V as seed.

update(seed?): void 

Returns

Nothing, but updates the internal state K and V value.

Argument Details

Example

drbg.update('e13af...');

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: JacobianPoint

The JacobianPoint class extends the BasePoint class for handling Jacobian coordinates on an Elliptic Curve. This class defines the properties and the methods needed to work with points in Jacobian coordinates.

The Jacobian coordinates represent a point (x, y, z) on an Elliptic Curve such that the usual (x, y) coordinates are given by (x/z^2, y/z^3).

Example

const pointJ = new JacobianPoint('3', '4', '1');
export default class JacobianPoint extends BasePoint {
    x: BigNumber;
    y: BigNumber;
    z: BigNumber;
    zOne: boolean;
    constructor(x: string | BigNumber | null, y: string | BigNumber | null, z: string | BigNumber | null) 
    toP(): Point 
    neg(): JacobianPoint 
    add(p: JacobianPoint): JacobianPoint 
    mixedAdd(p: Point): JacobianPoint 
    dblp(pow: number): JacobianPoint 
    dbl(): JacobianPoint 
    eq(p: Point | JacobianPoint): boolean 
    eqXToP(x: BigNumber): boolean 
    inspect(): string 
    isInfinity(): boolean 
}

See also: BasePoint, BigNumber, Point

Constructor

Constructs a new JacobianPoint instance.

constructor(x: string | BigNumber | null, y: string | BigNumber | null, z: string | BigNumber | null) 

See also: BigNumber

Argument Details

Example

const pointJ1 = new JacobianPoint(null, null, null); // creates point at infinity
const pointJ2 = new JacobianPoint('3', '4', '1'); // creates point (3, 4, 1)

Property x

The x coordinate of the point in the Jacobian form.

x: BigNumber

See also: BigNumber

Property y

The y coordinate of the point in the Jacobian form.

y: BigNumber

See also: BigNumber

Property z

The z coordinate of the point in the Jacobian form.

z: BigNumber

See also: BigNumber

Property zOne

Flag that indicates if the z coordinate is one.

zOne: boolean

Method add

Addition operation in the Jacobian coordinates. It takes a Jacobian point as an argument and returns a new Jacobian point as a result of the addition. In the special cases, when either one of the points is the point at infinity, it will return the other point.

add(p: JacobianPoint): JacobianPoint 

See also: JacobianPoint

Returns

Returns a new Jacobian point as the result of the addition.

Argument Details

Example

const p1 = new JacobianPoint(x1, y1, z1)
const p2 = new JacobianPoint(x2, y2, z2)
const result = p1.add(p2)

Method dbl

Point doubling operation in the Jacobian coordinates. A special case is when the point is the point at infinity, in this case, this function will return the point itself.

dbl(): JacobianPoint 

See also: JacobianPoint

Returns

Returns a new Jacobian point as the result of the doubling.

Example

const jp = new JacobianPoint(x, y, z)
const result = jp.dbl()

Method dblp

Multiple doubling operation. It doubles the Jacobian point as many times as the pow parameter specifies. If pow is 0 or the point is the point at infinity, it will return the point itself.

dblp(pow: number): JacobianPoint 

See also: JacobianPoint

Returns

Returns a new Jacobian point as the result of multiple doublings.

Argument Details

Example

const jp = new JacobianPoint(x, y, z)
const result = jp.dblp(3)

Method eq

Equality check operation. It checks whether the affine or Jacobian point is equal to this Jacobian point.

eq(p: Point | JacobianPoint): boolean 

See also: JacobianPoint, Point

Returns

Returns true if the points are equal, otherwise returns false.

Argument Details

Example

const jp1 = new JacobianPoint(x1, y1, z1)
const jp2 = new JacobianPoint(x2, y2, z2)
const areEqual = jp1.eq(jp2)

Method eqXToP

Equality check operation in relation to an x coordinate of a point in projective coordinates. It checks whether the x coordinate of the Jacobian point is equal to the provided x coordinate of a point in projective coordinates.

eqXToP(x: BigNumber): boolean 

See also: BigNumber

Returns

Returns true if the x coordinates are equal, otherwise returns false.

Argument Details

Example

const jp = new JacobianPoint(x1, y1, z1)
const isXEqual = jp.eqXToP(x2)

Method inspect

Returns the string representation of the JacobianPoint instance.

inspect(): string 

Returns

Returns the string description of the JacobianPoint. If the JacobianPoint represents a point at infinity, the return value of this function is ‘'. For a normal point, it returns the string description format as '<EC JPoint x: x-coordinate y: y-coordinate z: z-coordinate>'.

Example

const point = new JacobianPoint('5', '6', '1');
console.log(point.inspect()); // Output: '<EC JPoint x: 5 y: 6 z: 1>'

Method isInfinity

Checks whether the JacobianPoint instance represents a point at infinity.

isInfinity(): boolean 

Returns

Returns true if the JacobianPoint’s z-coordinate equals to zero (which represents the point at infinity in Jacobian coordinates). Returns false otherwise.

Example

const point = new JacobianPoint('5', '6', '0');
console.log(point.isInfinity()); // Output: true

Method mixedAdd

Mixed addition operation. This function combines the standard point addition with the transformation from the affine to Jacobian coordinates. It first converts the affine point to Jacobian, and then preforms the addition.

mixedAdd(p: Point): JacobianPoint 

See also: JacobianPoint, Point

Returns

Returns the result of the mixed addition as a new Jacobian point.

Argument Details

Example

const jp = new JacobianPoint(x1, y1, z1)
const ap = new Point(x2, y2)
const result = jp.mixedAdd(ap)

Method neg

Negation operation. It returns the additive inverse of the Jacobian point.

neg(): JacobianPoint 

See also: JacobianPoint

Returns

Returns a new Jacobian point as the result of the negation.

Example

const jp = new JacobianPoint(x, y, z)
const result = jp.neg()

Method toP

Converts the JacobianPoint object instance to standard affine Point format and returns Point type.

toP(): Point 

See also: Point

Returns

The Point(affine) object representing the same point as the original JacobianPoint.

If the initial JacobianPoint represents point at infinity, an instance of Point at infinity is returned.

Example

const pointJ = new JacobianPoint('3', '4', '1');
const pointP = pointJ.toP();  // The point in affine coordinates.

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: K256

A class representing K-256, a prime number with optimizations, specifically used in the secp256k1 curve. It extends the functionalities of the Mersenne class. K-256 prime is represented as ‘ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f’

Example

const k256 = new K256();
export default class K256 extends Mersenne {
    constructor() 
    split(input: BigNumber, output: BigNumber): void 
    imulK(num: BigNumber): BigNumber 
}

See also: BigNumber, Mersenne

Constructor

Constructor for the K256 class. Creates an instance of K256 using the super constructor from Mersenne.

constructor() 

Example

const k256 = new K256();

Method imulK

Multiplies a BigNumber (‘num’) with the constant ‘K’ in-place and returns the result. ‘K’ is equal to 0x1000003d1 or in decimal representation: [ 64, 977 ].

imulK(num: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the mutated BigNumber after multiplication.

Argument Details

Example

const number = new BigNumber(12345);
const result = k256.imulK(number);

Method split

Splits a BigNumber into a new BigNumber based on specific computation rules. This method modifies the input and output big numbers.

split(input: BigNumber, output: BigNumber): void 

See also: BigNumber

Argument Details

Example

const input = new BigNumber(3456);
const output = new BigNumber(0);
k256.split(input, output);

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: KeyShares

Example

const key = PrivateKey.fromShares(shares)
export class KeyShares {
    points: PointInFiniteField[];
    threshold: number;
    integrity: string;
    constructor(points: PointInFiniteField[], threshold: number, integrity: string) 
    static fromBackupFormat(shares: string[]): KeyShares 
    toBackupFormat(): string[] 
}

See also: PointInFiniteField

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: Mersenne

A representation of a pseudo-Mersenne prime. A pseudo-Mersenne prime has the general form 2^n - k, where n and k are integers.

export default class Mersenne {
    name: string;
    p: BigNumber;
    k: BigNumber;
    n: number;
    constructor(name: string, p: string) 
    ireduce(num: BigNumber): BigNumber 
    split(input: BigNumber, out: BigNumber): void 
    imulK(num: BigNumber): BigNumber 
}

See also: BigNumber

Constructor

constructor(name: string, p: string) 

Argument Details

Example

const mersenne = new Mersenne('M31', '7FFFFFFF');

Property k

The constant subtracted from 2^n to derive a pseudo-Mersenne prime.

k: BigNumber

See also: BigNumber

Property n

The exponent which determines the magnitude of the prime.

n: number

Property name

The identifier for the Mersenne instance.

name: string

Property p

BigNumber equivalent to 2^n - k.

p: BigNumber

See also: BigNumber

Method imulK

Performs an in-place multiplication of the parameter by constant k.

imulK(num: BigNumber): BigNumber 

See also: BigNumber

Returns

The result of the multiplication, in BigNumber format.

Argument Details

Example

const multiplied = mersenne.imulK(new BigNumber('2345', 16));

Method ireduce

Reduces an input BigNumber in place, under the assumption that it is less than the square of the pseudo-Mersenne prime.

ireduce(num: BigNumber): BigNumber 

See also: BigNumber

Returns

The reduced BigNumber.

Argument Details

Example

const reduced = mersenne.ireduce(new BigNumber('2345', 16));

Method split

Shifts bits of the input BigNumber to the right, in place, to meet the magnitude of the pseudo-Mersenne prime.

split(input: BigNumber, out: BigNumber): void 

See also: BigNumber

Argument Details

Example

mersenne.split(new BigNumber('2345', 16), new BigNumber());

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: MontgomoryMethod

Represents a Montgomery reduction context, which is a mathematical method for performing modular multiplication without division.

Montgomery reduction is an algorithm used mainly in cryptography which can help to speed up calculations in contexts where there are many repeated computations.

This class extends the ReductionContext class.

export default class MontgomoryMethod extends ReductionContext {
    shift: number;
    r: BigNumber;
    r2: BigNumber;
    rinv: BigNumber;
    minv: BigNumber;
    constructor(m: BigNumber | "k256") 
    convertTo(num: BigNumber): BigNumber 
    convertFrom(num: BigNumber): BigNumber 
    imul(a: BigNumber, b: BigNumber): BigNumber 
    mul(a: BigNumber, b: BigNumber): BigNumber 
    invm(a: BigNumber): BigNumber 
}

See also: BigNumber, ReductionContext

Constructor

constructor(m: BigNumber | "k256") 

See also: BigNumber

Argument Details

Property minv

The modular multiplicative inverse of m mod r.

minv: BigNumber

See also: BigNumber

Property r

The 2^shift, shifted left by the bit length of modulus m.

r: BigNumber

See also: BigNumber

Property r2

The square of r modulo m.

r2: BigNumber

See also: BigNumber

Property rinv

The modular multiplicative inverse of r mod m.

rinv: BigNumber

See also: BigNumber

Property shift

The number of bits in the modulus.

shift: number

Method convertFrom

Converts a number from the Montgomery domain back to the original domain.

convertFrom(num: BigNumber): BigNumber 

See also: BigNumber

Returns

The result of the conversion from the Montgomery domain.

Argument Details

Example

const montMethod = new MontgomoryMethod(m);
const convertedNum = montMethod.convertFrom(num);

Method convertTo

Converts a number into the Montgomery domain.

convertTo(num: BigNumber): BigNumber 

See also: BigNumber

Returns

The result of the conversion into the Montgomery domain.

Argument Details

Example

const montMethod = new MontgomoryMethod(m);
const convertedNum = montMethod.convertTo(num);

Method imul

Performs an in-place multiplication of two numbers in the Montgomery domain.

imul(a: BigNumber, b: BigNumber): BigNumber 

See also: BigNumber

Returns

The result of the in-place multiplication.

Argument Details

Example

const montMethod = new MontgomoryMethod(m);
const product = montMethod.imul(a, b);

Method invm

Calculates the modular multiplicative inverse of a number in the Montgomery domain.

invm(a: BigNumber): BigNumber 

See also: BigNumber

Returns

The modular multiplicative inverse of ‘a’.

Argument Details

Example

const montMethod = new MontgomoryMethod(m);
const inverse = montMethod.invm(a);

Method mul

Performs the multiplication of two numbers in the Montgomery domain.

mul(a: BigNumber, b: BigNumber): BigNumber 

See also: BigNumber

Returns

The result of the multiplication.

Argument Details

Example

const montMethod = new MontgomoryMethod(m);
const product = montMethod.mul(a, b);

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: Point

Point class is a representation of an elliptic curve point with affine coordinates. It extends the functionality of BasePoint and carries x, y coordinates of point on the curve. It also introduces new methods for handling Point operations in elliptic curve.

export default class Point extends BasePoint {
    x: BigNumber | null;
    y: BigNumber | null;
    inf: boolean;
    static fromDER(bytes: number[]): Point 
    static fromString(str: string): Point 
    static redSqrtOptimized(y2: BigNumber): BigNumber 
    static fromX(x: BigNumber | number | number[] | string, odd: boolean): Point 
    static fromJSON(obj: string | any[], isRed: boolean): Point 
    constructor(x: BigNumber | number | number[] | string | null, y: BigNumber | number | number[] | string | null, isRed: boolean = true) 
    validate(): boolean 
    encode(compact: boolean = true, enc?: "hex"): number[] | string 
    toString(): string 
    toJSON(): [
        BigNumber | null,
        BigNumber | null,
        {
            doubles: {
                step: any;
                points: any[];
            } | undefined;
            naf: {
                wnd: any;
                points: any[];
            } | undefined;
        }?
    ] 
    inspect(): string 
    isInfinity(): boolean 
    add(p: Point): Point 
    dbl(): Point 
    getX(): BigNumber 
    getY(): BigNumber 
    mul(k: BigNumber | number | number[] | string): Point 
    mulAdd(k1: BigNumber, p2: Point, k2: BigNumber): Point 
    jmulAdd(k1: BigNumber, p2: Point, k2: BigNumber): JPoint 
    eq(p: Point): boolean 
    neg(_precompute?: boolean): Point 
    dblp(k: number): Point 
    toJ(): JPoint 
}

See also: BasePoint, BigNumber, encode

Constructor

constructor(x: BigNumber | number | number[] | string | null, y: BigNumber | number | number[] | string | null, isRed: boolean = true) 

See also: BigNumber

Argument Details

Example

new Point('abc123', 'def456');
new Point(null, null); // Generates Infinity point.

Property inf

Flag to record if the point is at infinity in the Elliptic Curve.

inf: boolean

Property x

The x-coordinate of the point.

x: BigNumber | null

See also: BigNumber

Property y

The y-coordinate of the point.

y: BigNumber | null

See also: BigNumber

Method add

Adds another Point to this Point, returning a new Point.

add(p: Point): Point 

See also: Point

Returns

A new Point that results from the addition.

Argument Details

Example

const p1 = new Point(1, 2);
const p2 = new Point(2, 3);
const result = p1.add(p2);

Method dbl

Doubles the current point.

dbl(): Point 

See also: Point

Example

const P = new Point('123', '456');
const result = P.dbl();

Method dblp

Performs the “doubling” operation on the Point a given number of times. This is used in elliptic curve operations to perform multiplication by 2, multiple times. If the point is at infinity, it simply returns the point because doubling a point at infinity is still infinity.

dblp(k: number): Point 

See also: Point

Returns

The Point after ‘k’ “doubling” operations have been performed.

Argument Details

Example

const p = new Point(5, 20);
const doubledPoint = p.dblp(10); // returns the point after "doubled" 10 times

Method encode

Encodes the coordinates of a point into an array or a hexadecimal string. The details of encoding are determined by the optional compact and enc parameters.

encode(compact: boolean = true, enc?: "hex"): number[] | string 

Returns

If enc is undefined, a byte array representation of the point will be returned. if enc is ‘hex’, a hexadecimal string representation of the point will be returned.

Argument Details

Throws

Will throw an error if the specified encoding method is not recognized. Expects ‘hex’.

Example

const aPoint = new Point(x, y);
const encodedPointArray = aPoint.encode();
const encodedPointHex = aPoint.encode(true, 'hex');

Method eq

Checks if the Point instance is equal to another given Point.

eq(p: Point): boolean 

See also: Point

Returns

Whether the two Point instances are equal. Both the ‘x’ and ‘y’ coordinates have to match, and both points have to either be valid or at infinity for equality. If both conditions are true, it returns true, else it returns false.

Argument Details

Example

const p1 = new Point(5, 20);
const p2 = new Point(5, 20);
const areEqual = p1.eq(p2); // returns true

Method fromDER

Creates a point object from a given Array. These numbers can represent coordinates in hex format, or points in multiple established formats. The function verifies the integrity of the provided data and throws errors if inconsistencies are found.

static fromDER(bytes: number[]): Point 

See also: Point

Returns

Returns a new point representing the given string.

Argument Details

Throws

Error If the point number[] value has a wrong length.

Error If the point format is unknown.

Example

const derPoint = [ 2, 18, 123, 108, 125, 83, 1, 251, 164, 214, 16, 119, 200, 216, 210, 193, 251, 193, 129, 67, 97, 146, 210, 216, 77, 254, 18, 6, 150, 190, 99, 198, 128 ];
const point = Point.fromDER(derPoint);

Method fromJSON

Generates a point from a serialized JSON object. The function accounts for different options in the JSON object, including precomputed values for optimization of EC operations, and calls another helper function to turn nested JSON points into proper Point objects.

static fromJSON(obj: string | any[], isRed: boolean): Point 

See also: Point

Returns

Returns a new point based on the deserialized JSON object.

Argument Details

Example

const serializedPoint = '{"x":52,"y":15}';
const point = Point.fromJSON(serializedPoint, true);

Method fromString

Creates a point object from a given string. This string can represent coordinates in hex format, or points in multiple established formats. The function verifies the integrity of the provided data and throws errors if inconsistencies are found.

static fromString(str: string): Point 

See also: Point

Returns

Returns a new point representing the given string.

Argument Details

Throws

Error If the point string value has a wrong length.

Error If the point format is unknown.

Example

const pointStr = 'abcdef';
const point = Point.fromString(pointStr);

Method fromX

Generates a point from an x coordinate and a boolean indicating whether the corresponding y coordinate is odd.

static fromX(x: BigNumber | number | number[] | string, odd: boolean): Point 

See also: BigNumber, Point

Returns

Returns the new point.

Argument Details

Throws

Error If the point is invalid.

Example

const xCoordinate = new BigNumber('10');
const point = Point.fromX(xCoordinate, true);

Method getX

Returns X coordinate of point

getX(): BigNumber 

See also: BigNumber

Example

const P = new Point('123', '456');
const x = P.getX();

Method getY

Returns X coordinate of point

getY(): BigNumber 

See also: BigNumber

Example

const P = new Point('123', '456');
const x = P.getX();

Method inspect

Provides the point coordinates in a human-readable string format for debugging purposes.

inspect(): string 

Returns

String of the format ‘<EC Point x: x-coordinate y: y-coordinate>’, or ‘' if the point is at infinity.

Example

const aPoint = new Point(x, y);
console.log(aPoint.inspect());

Method isInfinity

Checks if the point is at infinity.

isInfinity(): boolean 

Returns

Returns whether or not the point is at infinity.

Example

const p = new Point(null, null);
console.log(p.isInfinity()); // outputs: true

Method jmulAdd

Performs the Jacobian multiplication and addition operation in a single step. Instead of returning a regular Point, the result is a JacobianPoint.

jmulAdd(k1: BigNumber, p2: Point, k2: BigNumber): JPoint 

See also: BigNumber, Point

Returns

A JacobianPoint that results from the combined multiplication and addition operation.

Argument Details

Example

const p1 = new Point(1, 2);
const p2 = new Point(2, 3);
const result = p1.jmulAdd(2, p2, 3);

Method mul

Multiplies this Point by a scalar value, returning a new Point.

mul(k: BigNumber | number | number[] | string): Point 

See also: BigNumber, Point

Returns

A new Point that results from the multiplication.

Argument Details

Example

const p = new Point(1, 2);
const result = p.mul(2); // this doubles the Point

Method mulAdd

Performs a multiplication and addition operation in a single step. Multiplies this Point by k1, adds the resulting Point to the result of p2 multiplied by k2.

mulAdd(k1: BigNumber, p2: Point, k2: BigNumber): Point 

See also: BigNumber, Point

Returns

A Point that results from the combined multiplication and addition operations.

Argument Details

Example

const p1 = new Point(1, 2);
const p2 = new Point(2, 3);
const result = p1.mulAdd(2, p2, 3);

Method neg

Negate a point. The negation of a point P is the mirror of P about x-axis.

neg(_precompute?: boolean): Point 

See also: Point

Example

const P = new Point('123', '456');
const result = P.neg();

Method toJ

Converts the point to a Jacobian point. If the point is at infinity, the corresponding Jacobian point will also be at infinity.

toJ(): JPoint 

Returns

Returns a new Jacobian point based on the current point.

Example

const point = new Point(xCoordinate, yCoordinate);
const jacobianPoint = point.toJ();

Method toJSON

Exports the x and y coordinates of the point, and the precomputed doubles and non-adjacent form (NAF) for optimization. The output is an array.

toJSON(): [
    BigNumber | null,
    BigNumber | null,
    {
        doubles: {
            step: any;
            points: any[];
        } | undefined;
        naf: {
            wnd: any;
            points: any[];
        } | undefined;
    }?
] 

See also: BigNumber

Returns

An Array where first two elements are the coordinates of the point and optional third element is an object with doubles and NAF points.

Example

const aPoint = new Point(x, y);
const jsonPoint = aPoint.toJSON();

Method toString

function toString() { [native code] }

Converts the point coordinates to a hexadecimal string. A wrapper method for encode. Byte 0x02 or 0x03 is used as prefix based on the ‘y’ coordinate being even or odd respectively.

toString(): string 

Returns

A hexadecimal string representation of the point coordinates.

Example

const aPoint = new Point(x, y);
const stringPoint = aPoint.toString();

Method validate

Validates if a point belongs to the curve. Follows the short Weierstrass equation for elliptic curves: y^2 = x^3 + ax + b.

validate(): boolean 

Returns

true if the point is on the curve, false otherwise.

Example

const aPoint = new Point(x, y);
const isValid = aPoint.validate();

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: PointInFiniteField

export class PointInFiniteField {
    x: BigNumber;
    y: BigNumber;
    constructor(x: BigNumber, y: BigNumber) 
    toString(): string 
    static fromString(str: string): PointInFiniteField 
}

See also: BigNumber

Method toString

function toString() { [native code] }

toString(): string 

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: Polynomial

Polynomial class

This class is used to create a polynomial with a given threshold and a private key. The polynomial is used to create shares of the private key.

Example

const key = new PrivateKey()
const threshold = 2
const polynomial = new Polynomial(key, threshold)
export default class Polynomial {
    readonly points: PointInFiniteField[];
    readonly threshold: number;
    constructor(points: PointInFiniteField[], threshold?: number) 
    static fromPrivateKey(key: PrivateKey, threshold: number): Polynomial 
    valueAt(x: BigNumber): BigNumber 
}

See also: BigNumber, PointInFiniteField, PrivateKey

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: PrivateKey

Represents a Private Key, which is a secret that can be used to generate signatures in a cryptographic system.

The PrivateKey class extends from the BigNumber class. It offers methods to create signatures, verify them, create a corresponding public key and derive a shared secret from a public key.

export default class PrivateKey extends BigNumber {
    static fromRandom(): PrivateKey 
    static fromString(str: string, base: number | "hex" = "hex"): PrivateKey 
    static fromHex(str: string): PrivateKey 
    static fromWif(wif: string, prefixLength: number = 1): PrivateKey 
    constructor(number: BigNumber | number | string | number[] = 0, base: number | "be" | "le" | "hex" = 10, endian: "be" | "le" = "be", modN: "apply" | "nocheck" | "error" = "apply") 
    checkInField(): {
        inField: boolean;
        modN: BigNumber;
    } 
    isValid(): boolean 
    sign(msg: number[] | string, enc?: "hex" | "utf8", forceLowS: boolean = true, customK?: ((iter: number) => BigNumber) | BigNumber): Signature 
    verify(msg: number[] | string, sig: Signature, enc?: "hex"): boolean 
    toPublicKey(): PublicKey 
    toWif(prefix: number[] = [128]): string 
    toAddress(prefix: number[] | string = [0]): string 
    toHex(): string 
    toString(base: number | "hex" = "hex", padding: number = 64): string 
    deriveSharedSecret(key: PublicKey): Point 
    deriveChild(publicKey: PublicKey, invoiceNumber: string): PrivateKey 
    toKeyShares(threshold: number, totalShares: number): KeyShares 
    toBackupShares(threshold: number, totalShares: number): string[] 
    static fromBackupShares(shares: string[]): PrivateKey 
    static fromKeyShares(keyShares: KeyShares): PrivateKey 
}

See also: BigNumber, KeyShares, Point, PublicKey, Signature, sign, toHex, verify

Constructor

constructor(number: BigNumber | number | string | number[] = 0, base: number | "be" | "le" | "hex" = 10, endian: "be" | "le" = "be", modN: "apply" | "nocheck" | "error" = "apply") 

See also: BigNumber

Argument Details

Example

import PrivateKey from './PrivateKey';
import BigNumber from './BigNumber';
const privKey = new PrivateKey(new BigNumber('123456', 10, 'be'));

Method checkInField

A utility function to check that the value of this PrivateKey lies in the field limited by curve.n

checkInField(): {
    inField: boolean;
    modN: BigNumber;
} 

See also: BigNumber

Returns

, modN } where modN is this PrivateKey’s current BigNumber value mod curve.n, and inField is true only if modN equals current BigNumber value.

Method deriveChild

Derives a child key with BRC-42.

deriveChild(publicKey: PublicKey, invoiceNumber: string): PrivateKey 

See also: PrivateKey, PublicKey

Returns

The derived child key.

Argument Details

Method deriveSharedSecret

Derives a shared secret from the public key.

deriveSharedSecret(key: PublicKey): Point 

See also: Point, PublicKey

Returns

The derived shared secret (a point on the curve).

Argument Details

Throws

Will throw an error if the public key is not valid.

Example

const privateKey = PrivateKey.fromRandom();
const publicKey = privateKey.toPublicKey();
const sharedSecret = privateKey.deriveSharedSecret(publicKey);

Method fromBackupShares

static fromBackupShares(shares: string[]): PrivateKey 

See also: PrivateKey

Returns

PrivateKey

Example

const share1 = '3znuzt7DZp8HzZTfTh5MF9YQKNX3oSxTbSYmSRGrH2ev.2Nm17qoocmoAhBTCs8TEBxNXCskV9N41rB2PckcgYeqV.2.35449bb9'
const share2 = 'Cm5fuUc39X5xgdedao8Pr1kvCSm8Gk7Cfenc7xUKcfLX.2juyK9BxCWn2DiY5JUAgj9NsQ77cc9bWksFyW45haXZm.2.35449bb9'

const recoveredKey = PrivateKey.fromBackupShares([share1, share2])

Method fromHex

Generates a private key from a hexadecimal string.

static fromHex(str: string): PrivateKey 

See also: PrivateKey

Returns

The generated Private Key instance.

Argument Details

Throws

If the string is not a valid hexadecimal or represents an invalid private key.

Method fromKeyShares

Combines shares to reconstruct the private key.

static fromKeyShares(keyShares: KeyShares): PrivateKey 

See also: KeyShares, PrivateKey

Returns

The reconstructed private key.

Argument Details

Method fromRandom

Generates a private key randomly.

static fromRandom(): PrivateKey 

See also: PrivateKey

Returns

The newly generated Private Key.

Example

const privateKey = PrivateKey.fromRandom();

Method fromString

Generates a private key from a string.

static fromString(str: string, base: number | "hex" = "hex"): PrivateKey 

See also: PrivateKey

Returns

The generated Private Key.

Argument Details

Throws

Will throw an error if the string is not valid.

Method fromWif

Generates a private key from a WIF (Wallet Import Format) string.

static fromWif(wif: string, prefixLength: number = 1): PrivateKey 

See also: PrivateKey

Returns

The generated Private Key.

Argument Details

Throws

Will throw an error if the string is not a valid WIF.

Method isValid

isValid(): boolean 

Returns

true if the PrivateKey’s current BigNumber value lies in the field limited by curve.n

Method sign

Signs a message using the private key.

sign(msg: number[] | string, enc?: "hex" | "utf8", forceLowS: boolean = true, customK?: ((iter: number) => BigNumber) | BigNumber): Signature 

See also: BigNumber, Signature

Returns

A digital signature generated from the hash of the message and the private key.

Argument Details

Example

const privateKey = PrivateKey.fromRandom();
const signature = privateKey.sign('Hello, World!');

Method toAddress

Base58Check encodes the hash of the public key associated with this private key with a prefix to indicate locking script type. Defaults to P2PKH for mainnet, otherwise known as a “Bitcoin Address”.

toAddress(prefix: number[] | string = [0]): string 

Returns

Returns the address encoding associated with the hash of the public key associated with this private key.

Argument Details

Example

const address = privkey.toAddress()
const address = privkey.toAddress('mainnet')
const testnetAddress = privkey.toAddress([0x6f])
const testnetAddress = privkey.toAddress('testnet')

Method toBackupShares

toBackupShares(threshold: number, totalShares: number): string[] 

Argument Details

Method toHex

Converts this PrivateKey to a hexadecimal string.

toHex(): string 

Returns

Returns a string representing the hexadecimal value of this BigNumber.

Argument Details

Example

const bigNumber = new BigNumber(255);
const hex = bigNumber.toHex();

Method toKeyShares

Splits the private key into shares using Shamir’s Secret Sharing Scheme.

toKeyShares(threshold: number, totalShares: number): KeyShares 

See also: KeyShares

Returns

An array of shares.

Argument Details

Example

const key = PrivateKey.fromRandom()
const shares = key.toKeyShares(2, 5)

Method toPublicKey

Converts the private key to its corresponding public key.

The public key is generated by multiplying the base point G of the curve and the private key.

toPublicKey(): PublicKey 

See also: PublicKey

Returns

The generated PublicKey.

Example

const privateKey = PrivateKey.fromRandom();
const publicKey = privateKey.toPublicKey();

Method toString

function toString() { [native code] }

Converts this PrivateKey to a string representation.

toString(base: number | "hex" = "hex", padding: number = 64): string 

Returns

A string representation of the PrivateKey in the specified base, padded to the specified length.

Argument Details

Method toWif

Converts the private key to a Wallet Import Format (WIF) string.

Base58Check encoding is used for encoding the private key. The prefix

toWif(prefix: number[] = [128]): string 

Returns

The WIF string.

Argument Details

Throws

Error(‘Value is out of field’) if current BigNumber value is out of field limited by curve.n

Example

const privateKey = PrivateKey.fromRandom();
const wif = privateKey.toWif();
const testnetWif = privateKey.toWif([0xef]);

Method verify

Verifies a message’s signature using the public key associated with this private key.

verify(msg: number[] | string, sig: Signature, enc?: "hex"): boolean 

See also: Signature

Returns

Whether or not the signature is valid.

Argument Details

Example

const privateKey = PrivateKey.fromRandom();
const signature = privateKey.sign('Hello, World!');
const isSignatureValid = privateKey.verify('Hello, World!', signature);

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: PublicKey

The PublicKey class extends the Point class. It is used in public-key cryptography to derive shared secret, verify message signatures, and encode the public key in the DER format. The class comes with static methods to generate PublicKey instances from private keys or from strings.

export default class PublicKey extends Point {
    static fromPrivateKey(key: PrivateKey): PublicKey 
    static fromString(str: string): PublicKey 
    static fromDER(bytes: number[]): PublicKey 
    constructor(x: Point | BigNumber | number | number[] | string | null, y: BigNumber | number | number[] | string | null = null, isRed: boolean = true) 
    deriveSharedSecret(priv: PrivateKey): Point 
    verify(msg: number[] | string, sig: Signature, enc?: "hex" | "utf8"): boolean 
    toDER(enc?: "hex" | undefined): number[] | string 
    toHash(enc?: "hex"): number[] | string 
    toAddress(prefix: number[] | string = [0]): string 
    deriveChild(privateKey: PrivateKey, invoiceNumber: string): PublicKey 
    static fromMsgHashAndCompactSignature(msgHash: BigNumber, signature: number[] | string, enc?: "hex" | "base64"): PublicKey 
}

See also: BigNumber, Point, PrivateKey, Signature, verify

Constructor

constructor(x: Point | BigNumber | number | number[] | string | null, y: BigNumber | number | number[] | string | null = null, isRed: boolean = true) 

See also: BigNumber, Point

Argument Details

Example

new PublicKey(point1);
new PublicKey('abc123', 'def456');

Method deriveChild

Derives a child key with BRC-42.

deriveChild(privateKey: PrivateKey, invoiceNumber: string): PublicKey 

See also: PrivateKey, PublicKey

Returns

The derived child key.

Argument Details

Method deriveSharedSecret

Derive a shared secret from a public key and a private key for use in symmetric encryption. This method multiplies the public key (an instance of Point) with a private key.

deriveSharedSecret(priv: PrivateKey): Point 

See also: Point, PrivateKey

Returns

Returns the Point representing the shared secret.

Argument Details

Throws

Will throw an error if the public key is not valid for ECDH secret derivation.

Example

const myPrivKey = new PrivateKey(...)
const sharedSecret = myPubKey.deriveSharedSecret(myPrivKey)

Method fromDER

Static factory method to create a PublicKey instance from a number array.

static fromDER(bytes: number[]): PublicKey 

See also: PublicKey

Returns

Returns the PublicKey created from the number array.

Argument Details

Example

const myPubKey = PublicKey.fromString("03....")

Method fromMsgHashAndCompactSignature

Takes an array of numbers or a string and returns a new PublicKey instance. This method will throw an error if the Compact encoding is invalid. If a string is provided, it is assumed to represent a hexadecimal sequence. compactByte value 27-30 means uncompressed public key. 31-34 means compressed public key. The range represents the recovery param which can be 0,1,2,3.

static fromMsgHashAndCompactSignature(msgHash: BigNumber, signature: number[] | string, enc?: "hex" | "base64"): PublicKey 

See also: BigNumber, PublicKey

Returns

A PublicKey instance derived from the message hash and compact signature.

Argument Details

Example

const publicKey = Signature.fromMsgHashAndCompactSignature(msgHash, 'IMOl2mVKfDgsSsHT4uIYBNN4e...', 'base64');

Method fromPrivateKey

Static factory method to derive a public key from a private key. It multiplies the generator point ‘g’ on the elliptic curve by the private key.

static fromPrivateKey(key: PrivateKey): PublicKey 

See also: PrivateKey, PublicKey

Returns

Returns the PublicKey derived from the given PrivateKey.

Argument Details

Example

const myPrivKey = new PrivateKey(...)
const myPubKey = PublicKey.fromPrivateKey(myPrivKey)

Method fromString

Static factory method to create a PublicKey instance from a string.

static fromString(str: string): PublicKey 

See also: PublicKey

Returns

Returns the PublicKey created from the string.

Argument Details

Example

const myPubKey = PublicKey.fromString("03....")

Method toAddress

Base58Check encodes the hash of the public key with a prefix to indicate locking script type. Defaults to P2PKH for mainnet, otherwise known as a “Bitcoin Address”.

toAddress(prefix: number[] | string = [0]): string 

Returns

Returns the address encoding associated with the hash of the public key.

Argument Details

Example

const address = pubkey.toAddress()
const address = pubkey.toAddress('mainnet')
const testnetAddress = pubkey.toAddress([0x6f])
const testnetAddress = pubkey.toAddress('testnet')

Method toDER

Encode the public key to DER (Distinguished Encoding Rules) format.

toDER(enc?: "hex" | undefined): number[] | string 

Returns

Returns the DER-encoded public key in number array or string.

Argument Details

Example

const derPublicKey = myPubKey.toDER()

Method toHash

Hash sha256 and ripemd160 of the public key.

toHash(enc?: "hex"): number[] | string 

Returns

Returns the hash of the public key.

Example

const publicKeyHash = pubkey.toHash()

Method verify

Verify a signature of a message using this public key.

verify(msg: number[] | string, sig: Signature, enc?: "hex" | "utf8"): boolean 

See also: Signature

Returns

Returns true if the signature is verified successfully, otherwise false.

Argument Details

Example

const myMessage = "Hello, world!"
const mySignature = new Signature(...)
const isVerified = myPubKey.verify(myMessage, mySignature)

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: RIPEMD160

An implementation of RIPEMD160 cryptographic hash function. Extends the BaseHash class. It provides a way to compute a ‘digest’ for any kind of input data; transforming the data into a unique output of fixed size. The output is deterministic; it will always be the same for the same input.

Example

const ripemd160 = new RIPEMD160();
export class RIPEMD160 extends BaseHash {
    h: number[];
    constructor() 
    _update(msg: number[], start: number): void 
    _digest(): number[] 
    _digestHex(): string 
}

Property h

Array that is updated iteratively as part of hashing computation.

h: number[]

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: Reader

export class Reader {
    public bin: number[];
    public pos: number;
    constructor(bin: number[] = [], pos: number = 0) 
    public eof(): boolean 
    public read(len = this.bin.length): number[] 
    public readReverse(len = this.bin.length): number[] 
    public readUInt8(): number 
    public readInt8(): number 
    public readUInt16BE(): number 
    public readInt16BE(): number 
    public readUInt16LE(): number 
    public readInt16LE(): number 
    public readUInt32BE(): number 
    public readInt32BE(): number 
    public readUInt32LE(): number 
    public readInt32LE(): number 
    public readUInt64BEBn(): BigNumber 
    public readUInt64LEBn(): BigNumber 
    public readVarIntNum(): number 
    public readVarInt(): number[] 
    public readVarIntBn(): BigNumber 
}

See also: BigNumber

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: ReductionContext

A base reduction engine that provides several arithmetic operations over big numbers under a modulus context. It’s particularly suitable for calculations required in cryptography algorithms and encoding schemas.

export default class ReductionContext {
    prime: Mersenne | null;
    m: BigNumber;
    constructor(m: BigNumber | "k256") 
    verify1(a: BigNumber): void 
    verify2(a: BigNumber, b: BigNumber): void 
    imod(a: BigNumber): BigNumber 
    neg(a: BigNumber): BigNumber 
    add(a: BigNumber, b: BigNumber): BigNumber 
    iadd(a: BigNumber, b: BigNumber): BigNumber 
    sub(a: BigNumber, b: BigNumber): BigNumber 
    isub(a: BigNumber, b: BigNumber): BigNumber 
    shl(a: BigNumber, num: number): BigNumber 
    imul(a: BigNumber, b: BigNumber): BigNumber 
    mul(a: BigNumber, b: BigNumber): BigNumber 
    isqr(a: BigNumber): BigNumber 
    sqr(a: BigNumber): BigNumber 
    sqrt(a: BigNumber): BigNumber 
    invm(a: BigNumber): BigNumber 
    pow(a: BigNumber, num: BigNumber): BigNumber 
    convertTo(num: BigNumber): BigNumber 
    convertFrom(num: BigNumber): BigNumber 
}

See also: BigNumber, Mersenne

Constructor

Constructs a new ReductionContext.

constructor(m: BigNumber | "k256") 

See also: BigNumber

Argument Details

Example

new ReductionContext(new BigNumber(11));
new ReductionContext('k256');

Property m

The modulus used for reduction operations.

m: BigNumber

See also: BigNumber

Property prime

The prime number utilised in the reduction context, typically an instance of Mersenne class.

prime: Mersenne | null

See also: Mersenne

Method add

Performs the addition operation on two BigNumbers in the reduction context.

add(a: BigNumber, b: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the result of ‘a + b’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(5));
context.add(new BigNumber(2), new BigNumber(4)); // Returns 1

Method convertFrom

Converts a BigNumber from reduction context to its regular form.

convertFrom(num: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the converted BigNumber in its regular form.

Argument Details

Example

const context = new ReductionContext(new BigNumber(7));
const a = context.convertTo(new BigNumber(8)); // 'a' is now 1 in the reduction context
context.convertFrom(a); // Returns 1

Method convertTo

Converts a BigNumber to its equivalent in the reduction context.

convertTo(num: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the converted BigNumber compatible with the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(7));
context.convertTo(new BigNumber(8)); // Returns 1 (8 % 7)

Method iadd

Performs an in-place addition operation on two BigNumbers in the reduction context in order to avoid creating a new BigNumber, it modifies the first one with the result.

iadd(a: BigNumber, b: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the modified ‘a’ after addition with ‘b’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(5));
const a = new BigNumber(2);
context.iadd(a, new BigNumber(4)); // Modifies 'a' to be 1

Method imod

Performs an in-place reduction of the given BigNumber by the modulus of the reduction context, ‘m’.

imod(a: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the reduced result.

Argument Details

Example

const context = new ReductionContext(new BigNumber(7));
context.imod(new BigNumber(19)); // Returns 5

Method imul

Performs in-place multiplication of two BigNumbers in the reduction context, modifying the first BigNumber with the result.

imul(a: BigNumber, b: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the modified ‘a’ after multiplication with ‘b’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(7));
const a = new BigNumber(3);
context.imul(a, new BigNumber(2)); // Modifies 'a' to be 6

Method invm

Calculates the multiplicative inverse of a BigNumber in the reduction context.

invm(a: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the multiplicative inverse of ‘a’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(11));
context.invm(new BigNumber(3)); // Returns 4 (3*4 mod 11 = 1)

Method isqr

Calculates the square of a BigNumber in the reduction context, modifying the original BigNumber with the result.

isqr(a: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the squared ‘a’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(7));
const a = new BigNumber(3);
context.isqr(a); // Modifies 'a' to be 2 (9 % 7 = 2)

Method isub

Performs in-place subtraction of one BigNumber from another in the reduction context, it modifies the first BigNumber with the result.

isub(a: BigNumber, b: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the modified ‘a’ after subtraction of ‘b’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(5));
const a = new BigNumber(4);
context.isub(a, new BigNumber(2)); // Modifies 'a' to be 2

Method mul

Multiplies two BigNumbers in the reduction context.

mul(a: BigNumber, b: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the result of ‘a * b’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(7));
context.mul(new BigNumber(3), new BigNumber(2)); // Returns 6

Method neg

Negates a BigNumber in the context of the modulus.

neg(a: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the negation of ‘a’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(7));
context.neg(new BigNumber(3)); // Returns 4

Method pow

Raises a BigNumber to a power in the reduction context.

pow(a: BigNumber, num: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the result of ‘a’ raised to the power of ‘num’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(7));
context.pow(new BigNumber(3), new BigNumber(2)); // Returns 2 (3^2 % 7)

Method shl

Performs bitwise shift left operation on a BigNumber in the reduction context.

shl(a: BigNumber, num: number): BigNumber 

See also: BigNumber

Returns

Returns the result of shifting ‘a’ left by ‘num’ positions in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(32));
context.shl(new BigNumber(4), 2); // Returns 16

Method sqr

Calculates the square of a BigNumber in the reduction context.

sqr(a: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the result of ‘a^2’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(7));
context.sqr(new BigNumber(3)); // Returns 2 (9 % 7 = 2)

Method sqrt

Calculates the square root of a BigNumber in the reduction context.

sqrt(a: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the square root of ‘a’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(9));
context.sqrt(new BigNumber(4)); // Returns 2

Method sub

Subtracts one BigNumber from another BigNumber in the reduction context.

sub(a: BigNumber, b: BigNumber): BigNumber 

See also: BigNumber

Returns

Returns the result of ‘a - b’ in the reduction context.

Argument Details

Example

const context = new ReductionContext(new BigNumber(7));
context.sub(new BigNumber(3), new BigNumber(2)); // Returns 1

Method verify1

Verifies that a BigNumber is positive and red. Throws an error if these conditions are not met.

verify1(a: BigNumber): void 

See also: BigNumber

Argument Details

Example

this.verify1(new BigNumber(10).toRed());
this.verify1(new BigNumber(-10).toRed()); //throws an Error
this.verify1(new BigNumber(10)); //throws an Error

Method verify2

Verifies that two BigNumbers are both positive and red. Also checks that they have the same reduction context. Throws an error if these conditions are not met.

verify2(a: BigNumber, b: BigNumber): void 

See also: BigNumber

Argument Details

Example

this.verify2(new BigNumber(10).toRed(this), new BigNumber(20).toRed(this));
this.verify2(new BigNumber(-10).toRed(this), new BigNumber(20).toRed(this)); //throws an Error
this.verify2(new BigNumber(10).toRed(this), new BigNumber(20)); //throws an Error

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: SHA1

An implementation of SHA1 cryptographic hash function. Extends the BaseHash class. It provides a way to compute a ‘digest’ for any kind of input data; transforming the data into a unique output of fixed size. The output is deterministic; it will always be the same for the same input.

Example

const sha1 = new SHA1();
export class SHA1 extends BaseHash {
    h: number[];
    W: number[];
    k: number[];
    constructor() 
    _update(msg: number[], start?: number): void 
    _digest(): number[] 
    _digestHex(): string 
}

Property W

Provides a way to recycle usage of the array memory.

W: number[]

Property h

The initial hash constants.

h: number[]

Property k

The round constants used for each round of SHA-1.

k: number[]

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: SHA1HMAC

export class SHA1HMAC {
    inner: SHA1;
    outer: SHA1;
    blockSize = 64;
    constructor(key: number[] | string) 
    update(msg: number[] | string, enc?: "hex"): SHA1HMAC 
    digest(): number[] 
    digestHex(): string 
}

See also: SHA1

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: SHA256

An implementation of SHA256 cryptographic hash function. Extends the BaseHash class. It provides a way to compute a ‘digest’ for any kind of input data; transforming the data into a unique output of fixed size. The output is deterministic; it will always be the same for the same input.

Example

const sha256 = new SHA256();
export class SHA256 extends BaseHash {
    h: number[];
    W: number[];
    k: number[];
    constructor() 
    _update(msg: number[], start?: number): void 
    _digest(): number[] 
    _digestHex(): string 
}

Property W

Provides a way to recycle usage of the array memory.

W: number[]

Property h

The initial hash constants

h: number[]

Property k

The round constants used for each round of SHA-256

k: number[]

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: SHA256HMAC

The SHA256HMAC class is used to create Hash-based Message Authentication Code (HMAC) using the SHA-256 cryptographic hash function.

HMAC is a specific type of MAC involving a cryptographic hash function and a secret cryptographic key. It may be used to simultaneously verify both the data integrity and the authenticity of a message.

This class also uses the SHA-256 cryptographic hash algorithm that produces a 256-bit (32-byte) hash value.

export class SHA256HMAC {
    inner: SHA256;
    outer: SHA256;
    blockSize = 64;
    outSize = 32;
    constructor(key: number[] | string) 
    update(msg: number[] | string, enc?: "hex"): SHA256HMAC 
    digest(): number[] 
    digestHex(): string 
}

See also: SHA256

Constructor

The constructor for the SHA256HMAC class.

It initializes the SHA256HMAC object and sets up the inner and outer padded keys. If the key size is larger than the blockSize, it is digested using SHA-256. If the key size is less than the blockSize, it is padded with zeroes.

constructor(key: number[] | string) 

Argument Details

Example

const myHMAC = new SHA256HMAC('deadbeef');

Property blockSize

The block size for the SHA-256 hash function, in bytes. It’s set to 64 bytes.

blockSize = 64

Property inner

Represents the inner hash of SHA-256.

inner: SHA256

See also: SHA256

Property outSize

The output size of the SHA-256 hash function, in bytes. It’s set to 32 bytes.

outSize = 32

Property outer

Represents the outer hash of SHA-256.

outer: SHA256

See also: SHA256

Method digest

Finalizes the HMAC computation and returns the resultant hash.

digest(): number[] 

Returns

Returns the digest of the hashed data. Can be a number array or a string.

Example

let hashedMessage = myHMAC.digest();

Method digestHex

Finalizes the HMAC computation and returns the resultant hash as a hex string.

digestHex(): string 

Returns

Returns the digest of the hashed data as a hex string

Example

let hashedMessage = myHMAC.digestHex();

Method update

Updates the SHA256HMAC object with part of the message to be hashed.

update(msg: number[] | string, enc?: "hex"): SHA256HMAC 

See also: SHA256HMAC

Returns

Returns the instance of SHA256HMAC for chaining calls.

Argument Details

Example

myHMAC.update('deadbeef', 'hex');

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: SHA512

An implementation of SHA512 cryptographic hash function. Extends the BaseHash class. It provides a way to compute a ‘digest’ for any kind of input data; transforming the data into a unique output of fixed size. The output is deterministic; it will always be the same for the same input.

Example

const sha512 = new SHA512();
export class SHA512 extends BaseHash {
    h: number[];
    W: number[];
    k: number[];
    constructor() 
    _prepareBlock(msg: number[], start: number): void 
    _update(msg: any, start: number): void 
    _digest(): number[] 
    _digestHex(): string 
}

Property W

Provides a way to recycle usage of the array memory.

W: number[]

Property h

The initial hash constants.

h: number[]

Property k

The round constants used for each round of SHA-512.

k: number[]

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: SHA512HMAC

The SHA512HMAC class is used to create Hash-based Message Authentication Code (HMAC) using the SHA-512 cryptographic hash function.

HMAC is a specific type of MAC involving a cryptographic hash function and a secret cryptographic key. It may be used to simultaneously verify both the data integrity and the authenticity of a message.

This class also uses the SHA-512 cryptographic hash algorithm that produces a 512-bit (64-byte) hash value.

export class SHA512HMAC {
    inner: SHA512;
    outer: SHA512;
    blockSize = 128;
    outSize = 32;
    constructor(key: number[] | string) 
    update(msg: number[] | string, enc?: "hex" | "utf8"): SHA512HMAC 
    digest(): number[] 
    digestHex(): string 
}

See also: SHA512

Constructor

The constructor for the SHA512HMAC class.

It initializes the SHA512HMAC object and sets up the inner and outer padded keys. If the key size is larger than the blockSize, it is digested using SHA-512. If the key size is less than the blockSize, it is padded with zeroes.

constructor(key: number[] | string) 

Argument Details

Example

const myHMAC = new SHA512HMAC('deadbeef');

Property blockSize

The block size for the SHA-512 hash function, in bytes. It’s set to 128 bytes.

blockSize = 128

Property inner

Represents the inner hash of SHA-512.

inner: SHA512

See also: SHA512

Property outSize

The output size of the SHA-512 hash function, in bytes. It’s set to 64 bytes.

outSize = 32

Property outer

Represents the outer hash of SHA-512.

outer: SHA512

See also: SHA512

Method digest

Finalizes the HMAC computation and returns the resultant hash.

digest(): number[] 

Returns

Returns the digest of the hashed data as a number array.

Example

let hashedMessage = myHMAC.digest();

Method digestHex

Finalizes the HMAC computation and returns the resultant hash as a hex string.

digestHex(): string 

Returns

Returns the digest of the hashed data as a hex string

Example

let hashedMessage = myHMAC.digestHex();

Method update

Updates the SHA512HMAC object with part of the message to be hashed.

update(msg: number[] | string, enc?: "hex" | "utf8"): SHA512HMAC 

See also: SHA512HMAC

Returns

Returns the instance of SHA512HMAC for chaining calls.

Argument Details

Example

myHMAC.update('deadbeef', 'hex');

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: Schnorr

Class representing the Schnorr Zero-Knowledge Proof (ZKP) protocol.

This class provides methods to generate and verify proofs that demonstrate knowledge of a secret without revealing it. Specifically, it allows one party to prove to another that they know the private key corresponding to a public key and have correctly computed a shared secret, without disclosing the private key itself.

The protocol involves two main methods:

The class utilizes elliptic curve cryptography (ECC) and the SHA-256 hash function to compute challenges within the proof.

Example

const schnorr = new Schnorr();
const a = PrivateKey.fromRandom(); // Prover's private key
const A = a.toPublicKey();         // Prover's public key
const b = PrivateKey.fromRandom(); // Other party's private key
const B = b.toPublicKey();         // Other party's public key
const S = B.mul(a);                // Shared secret

// Prover generates the proof
const proof = schnorr.generateProof(a, A, B, S);

// Verifier verifies the proof
const isValid = schnorr.verifyProof(A.point, B.point, S.point, proof);
console.log(`Proof is valid: ${isValid}`);
export default class Schnorr {
    constructor() 
    generateProof(aArg: PrivateKey, AArg: PublicKey, BArg: PublicKey, S: Point): {
        R: Point;
        SPrime: Point;
        z: BigNumber;
    } 
    verifyProof(A: Point, B: Point, S: Point, proof: {
        R: Point;
        SPrime: Point;
        z: BigNumber;
    }): boolean 
}

See also: BigNumber, Point, PrivateKey, PublicKey

Method generateProof

Generates a proof that demonstrates the link between public key A and shared secret S

generateProof(aArg: PrivateKey, AArg: PublicKey, BArg: PublicKey, S: Point): {
    R: Point;
    SPrime: Point;
    z: BigNumber;
} 

See also: BigNumber, Point, PrivateKey, PublicKey

Returns

Proof (R, S’, z)

Argument Details

Method verifyProof

Verifies the proof of the link between public key A and shared secret S

verifyProof(A: Point, B: Point, S: Point, proof: {
    R: Point;
    SPrime: Point;
    z: BigNumber;
}): boolean 

See also: BigNumber, Point

Returns

True if the proof is valid, false otherwise

Argument Details

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: Signature

Represents a digital signature.

A digital signature is a mathematical scheme for verifying the authenticity of digital messages or documents. In many scenarios, it is equivalent to a handwritten signature or stamped seal. The signature pair (R, S) corresponds to the raw ECDSA (Elliptic Curve Digital Signature Algorithm) signature. Signatures are often serialized into a format known as ‘DER encoding’ for transmission.

export default class Signature {
    r: BigNumber;
    s: BigNumber;
    static fromDER(data: number[] | string, enc?: "hex" | "base64"): Signature 
    static fromCompact(data: number[] | string, enc?: "hex" | "base64"): Signature 
    constructor(r: BigNumber, s: BigNumber) 
    verify(msg: number[] | string, key: PublicKey, enc?: "hex"): boolean 
    toString(enc?: "hex" | "base64"): number[] | string 
    toDER(enc?: "hex" | "base64"): number[] | string 
    toCompact(recovery: number, compressed: boolean, enc?: "hex" | "base64"): number[] | string 
    RecoverPublicKey(recovery: number, e: BigNumber): PublicKey 
    CalculateRecoveryFactor(pubkey: PublicKey, msgHash: BigNumber): number 
}

See also: BigNumber, PublicKey, verify

Constructor

Creates an instance of the Signature class.

constructor(r: BigNumber, s: BigNumber) 

See also: BigNumber

Argument Details

Example

const r = new BigNumber('208755674028...');
const s = new BigNumber('564745627577...');
const signature = new Signature(r, s);

Method CalculateRecoveryFactor

Calculates the recovery factor which will work for a particular public key and message hash. This method will return the recovery factor if it finds a valid recovery factor. If it does not find a valid recovery factor, it will throw an error. The recovery factor is a number between 0 and 3.

CalculateRecoveryFactor(pubkey: PublicKey, msgHash: BigNumber): number 

See also: BigNumber, PublicKey

Returns

the recovery factor: number /

Argument Details

Example

const recovery = signature.CalculateRecoveryFactor(publicKey, msgHash);

Method RecoverPublicKey

Recovers the public key from a signature. This method will return the public key if it finds a valid public key. If it does not find a valid public key, it will throw an error. The recovery factor is a number between 0 and 3.

RecoverPublicKey(recovery: number, e: BigNumber): PublicKey 

See also: BigNumber, PublicKey

Returns

The public key associated with the signature.

Argument Details

Example

const publicKey = signature.RecoverPublicKey(0, msgHash);

Method fromCompact

Takes an array of numbers or a string and returns a new Signature instance. This method will throw an error if the Compact encoding is invalid. If a string is provided, it is assumed to represent a hexadecimal sequence. compactByte value 27-30 means uncompressed public key. 31-34 means compressed public key. The range represents the recovery param which can be 0,1,2,3. We could support recovery functions in future if there’s demand.

static fromCompact(data: number[] | string, enc?: "hex" | "base64"): Signature 

See also: Signature

Returns

The decoded data in the form of Signature instance.

Argument Details

Example

const signature = Signature.fromCompact('1b18c1f5502f8...', 'hex');

Method fromDER

Takes an array of numbers or a string and returns a new Signature instance. This method will throw an error if the DER encoding is invalid. If a string is provided, it is assumed to represent a hexadecimal sequence.

static fromDER(data: number[] | string, enc?: "hex" | "base64"): Signature 

See also: Signature

Returns

The decoded data in the form of Signature instance.

Argument Details

Example

const signature = Signature.fromDER('30440220018c1f5502f8...', 'hex');

Method toCompact

Converts an instance of Signature into Compact encoding.

If the encoding parameter is set to ‘hex’, the function will return a hex string. If ‘base64’, it will return a base64 string. Otherwise, it will return an array of numbers.

toCompact(recovery: number, compressed: boolean, enc?: "hex" | "base64"): number[] | string 

Returns

The current instance in DER encoding.

Argument Details

Example

const compact = signature.toCompact(3, true, 'base64');

Method toDER

Converts an instance of Signature into DER encoding.

If the encoding parameter is set to ‘hex’, the function will return a hex string. If ‘base64’, it will return a base64 string. Otherwise, it will return an array of numbers.

toDER(enc?: "hex" | "base64"): number[] | string 

Returns

The current instance in DER encoding.

Argument Details

Example

const der = signature.toDER('hex');

Method toString

function toString() { [native code] }

Converts an instance of Signature into DER encoding. An alias for the toDER method.

If the encoding parameter is set to ‘hex’, the function will return a hex string. If ‘base64’, it will return a base64 string. Otherwise, it will return an array of numbers.

toString(enc?: "hex" | "base64"): number[] | string 

Returns

The current instance in DER encoding.

Argument Details

Example

const der = signature.toString('base64');

Method verify

Verifies a digital signature.

This method will return true if the signature, key, and message hash match. If the data or key do not match the signature, the function returns false.

verify(msg: number[] | string, key: PublicKey, enc?: "hex"): boolean 

See also: PublicKey

Returns

A boolean representing whether the signature is valid.

Argument Details

Example

const msg = 'The quick brown fox jumps over the lazy dog';
const publicKey = PublicKey.fromString('04188ca1050...');
const isVerified = signature.verify(msg, publicKey);

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: SymmetricKey

SymmetricKey is a class that extends the BigNumber class and implements symmetric encryption and decryption methods. Symmetric-Key encryption is a form of encryption where the same key is used to encrypt and decrypt the message. It leverages the Advanced Encryption Standard Galois/Counter Mode (AES-GCM) for encryption and decryption of messages.

export default class SymmetricKey extends BigNumber {
    static fromRandom(): SymmetricKey 
    encrypt(msg: number[] | string, enc?: "hex"): string | number[] 
    decrypt(msg: number[] | string, enc?: "hex" | "utf8"): string | number[] 
}

See also: BigNumber, decrypt, encrypt

Method decrypt

Decrypts a given AES-GCM encrypted message using the same key that was used for encryption. The method extracts the IV and the authentication tag from the encrypted message, then attempts to decrypt it. If the decryption fails (e.g., due to message tampering), an error is thrown.

decrypt(msg: number[] | string, enc?: "hex" | "utf8"): string | number[] 

Returns

Returns the decrypted message as a string or an array of numbers, depending on enc argument. If absent, an array of numbers is returned.

Argument Details

Throws

Will throw an error if the decryption fails, likely due to message tampering or incorrect decryption key.

Example

const key = new SymmetricKey(1234);
const decryptedMessage = key.decrypt(encryptedMessage, 'utf8');

Method encrypt

Encrypts a given message using AES-GCM encryption. The generated Initialization Vector (IV) is attached to the encrypted message for decryption purposes. The OpenSSL format of |IV|encryptedContent|authTag| is used.

encrypt(msg: number[] | string, enc?: "hex"): string | number[] 

Returns

Returns the encrypted message as a string or an array of numbers, depending on enc argument.

Argument Details

Example

const key = new SymmetricKey(1234);
const encryptedMessage = key.encrypt('plainText', 'utf8');

Method fromRandom

Generates a symmetric key randomly.

static fromRandom(): SymmetricKey 

See also: SymmetricKey

Returns

The newly generated Symmetric Key.

Example

const symmetricKey = SymmetricKey.fromRandom();

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: TransactionSignature

export default class TransactionSignature extends Signature {
    public static readonly SIGHASH_ALL = 1;
    public static readonly SIGHASH_NONE = 2;
    public static readonly SIGHASH_SINGLE = 3;
    public static readonly SIGHASH_FORKID = 64;
    public static readonly SIGHASH_ANYONECANPAY = 128;
    scope: number;
    static format(params: {
        sourceTXID: string;
        sourceOutputIndex: number;
        sourceSatoshis: number;
        transactionVersion: number;
        otherInputs: TransactionInput[];
        outputs: TransactionOutput[];
        inputIndex: number;
        subscript: Script;
        inputSequence: number;
        lockTime: number;
        scope: number;
    }): number[] 
    static fromChecksigFormat(buf: number[]): TransactionSignature 
    constructor(r: BigNumber, s: BigNumber, scope: number) 
    public hasLowS(): boolean 
    toChecksigFormat(): number[] 
}

See also: BigNumber, Script, Signature, TransactionInput, TransactionOutput

Method hasLowS

Compares to bitcoind’s IsLowDERSignature See also Ecdsa signature algorithm which enforces this. See also Bip 62, “low S values in signatures”

public hasLowS(): boolean 

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Class: Writer

export class Writer {
    public bufs: number[][];
    constructor(bufs?: number[][]) 
    getLength(): number 
    toArray(): number[] 
    write(buf: number[]): this 
    writeReverse(buf: number[]): this 
    writeUInt8(n: number): this 
    writeInt8(n: number): this 
    writeUInt16BE(n: number): this 
    writeInt16BE(n: number): this 
    writeUInt16LE(n: number): this 
    writeInt16LE(n: number): this 
    writeUInt32BE(n: number): this 
    writeInt32BE(n: number): this 
    writeUInt32LE(n: number): this 
    writeInt32LE(n: number): this 
    writeUInt64BEBn(bn: BigNumber): this 
    writeUInt64LEBn(bn: BigNumber): this 
    writeUInt64LE(n: number): this 
    writeVarIntNum(n: number): this 
    writeVarIntBn(bn: BigNumber): this 
    static varIntNum(n: number): number[] 
    static varIntBn(bn: BigNumber): number[] 
}

See also: BigNumber, toArray

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Functions

 
AES
AESGCM
AESGCMDecrypt
ghash
pbkdf2
toArray
toBase64

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Function: AES

export function AES(input: number[], key: number[]): number[] 

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Function: AESGCM

export function AESGCM(plainText: number[], additionalAuthenticatedData: number[], initializationVector: number[], key: number[]): {
    result: number[];
    authenticationTag: number[];
} 

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Function: AESGCMDecrypt

export function AESGCMDecrypt(cipherText: number[], additionalAuthenticatedData: number[], initializationVector: number[], authenticationTag: number[], key: number[]): number[] | null 

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Function: ghash

export function ghash(input: number[], hashSubKey: number[]): number[] 

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Function: pbkdf2

Limited SHA-512-only PBKDF2 function for use in deprecated BIP39 code.

export function pbkdf2(password: number[], salt: number[], iterations: number, keylen: number, digest = "sha512"): number[] 

Returns

The computed key

Argument Details

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Function: toArray

export function toArray(msg: number[] | string, enc?: "hex" | "utf8"): number[] 

Returns

array of byte values from msg. If msg is an array, a copy is returned.

Argument Details

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Function: toBase64

Converts an array of bytes (each between 0 and 255) into a base64 encoded string.

Example

const bytes = [72, 101, 108, 108, 111]; // Represents the string "Hello"
console.log(toBase64(bytes)); // Outputs: SGVsbG8=
export function toBase64(byteArray: number[]): string 

Returns

The base64 encoded string.

Argument Details

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Types

Enums

Variables

     
checkBit minimallyEncode sign
encode multiply toArray
exclusiveOR rightShift toBase58
fromBase58 ripemd160 toBase58Check
fromBase58Check sha1 toHex
getBytes sha256 toUTF8
hash160 sha256hmac verify
hash256 sha512 zero2
incrementLeastSignificantThirtyTwoBits sha512hmac  

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: checkBit

checkBit = function (byteArray: number[], byteIndex: number, bitIndex: number): 1 | 0 {
    return (byteArray[byteIndex] & (1 << bitIndex)) !== 0 ? 1 : 0;
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: encode

encode = (arr: number[], enc?: "hex" | "utf8"): string | number[] => {
    switch (enc) {
        case "hex":
            return toHex(arr);
        case "utf8":
            return toUTF8(arr);
        default:
            return arr;
    }
}

See also: toHex, toUTF8

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: exclusiveOR

exclusiveOR = function (block0: number[], block1: number[]): number[] {
    let i;
    const result = [];
    for (i = 0; i < block0.length; i++) {
        result[i] = block0[i] ^ block1[i];
    }
    return result;
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: fromBase58

fromBase58 = (str: string): number[] => {
    if (str === "" || typeof str !== "string") {
        throw new Error(`Expected base58 string but got “${str}”`);
    }
    const match: string[] | null = str.match(/[IOl0]/gmu);
    if (match !== null) {
        throw new Error(`Invalid base58 character “${match.join("")}”`);
    }
    const lz = str.match(/^1+/gmu);
    const psz: number = (lz !== null) ? lz[0].length : 0;
    const size = ((str.length - psz) * (Math.log(58) / Math.log(256)) + 1) >>> 0;
    const uint8 = new Uint8Array([
        ...new Uint8Array(psz),
        ...(str.match(/./gmu) ?? [])
            .map((i) => base58chars.indexOf(i))
            .reduce((acc, i) => {
            acc = acc.map((j) => {
                const x = j * 58 + i;
                i = x >> 8;
                return x;
            });
            return acc;
        }, new Uint8Array(size))
            .reverse()
            .filter(((lastValue) => (value) => (lastValue = lastValue || value))(false))
    ]);
    return [...uint8];
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: fromBase58Check

fromBase58Check = (str: string, enc?: "hex", prefixLength: number = 1): {
    data: number[] | string;
    prefix: number[] | string;
} => {
    const bin = fromBase58(str);
    let prefix: string | number[] = bin.slice(0, prefixLength);
    let data: string | number[] = bin.slice(prefixLength, -4);
    let hash = [...prefix, ...data];
    hash = hash256(hash);
    bin.slice(-4).forEach((check, index) => {
        if (check !== hash[index]) {
            throw new Error("Invalid checksum");
        }
    });
    if (enc === "hex") {
        prefix = toHex(prefix);
        data = toHex(data);
    }
    return { prefix, data };
}

See also: fromBase58, hash256, toHex

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: getBytes

getBytes = function (numericValue: number): number[] {
    return [
        (numericValue & 4278190080) >>> 24,
        (numericValue & 16711680) >> 16,
        (numericValue & 65280) >> 8,
        numericValue & 255
    ];
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: hash160

hash160 = (msg: number[] | string, enc?: "hex" | "utf8"): number[] => {
    const first = new SHA256().update(msg, enc).digest();
    return new RIPEMD160().update(first).digest();
}

See also: RIPEMD160, SHA256

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: hash256

hash256 = (msg: number[] | string, enc?: "hex" | "utf8"): number[] => {
    const first = new SHA256().update(msg, enc).digest();
    return new SHA256().update(first).digest();
}

See also: SHA256

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: incrementLeastSignificantThirtyTwoBits

incrementLeastSignificantThirtyTwoBits = function (block: number[]): number[] {
    let i;
    const result = block.slice();
    for (i = 15; i !== 11; i--) {
        result[i] = result[i] + 1;
        if (result[i] === 256) {
            result[i] = 0;
        }
        else {
            break;
        }
    }
    return result;
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: minimallyEncode

minimallyEncode = (buf: number[]): number[] => {
    if (buf.length === 0) {
        return buf;
    }
    const last = buf[buf.length - 1];
    if ((last & 127) !== 0) {
        return buf;
    }
    if (buf.length === 1) {
        return [];
    }
    if ((buf[buf.length - 2] & 128) !== 0) {
        return buf;
    }
    for (let i = buf.length - 1; i > 0; i--) {
        if (buf[i - 1] !== 0) {
            if ((buf[i - 1] & 128) !== 0) {
                buf[i] = last;
                return buf.slice(0, i + 1);
            }
            else {
                buf[i - 1] |= last;
                return buf.slice(0, i);
            }
        }
    }
    return [];
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: multiply

multiply = function (block0: number[], block1: number[]): number[] {
    let i;
    let j;
    let v = block1.slice();
    let z = createZeroBlock(16);
    for (i = 0; i < 16; i++) {
        for (j = 7; j !== -1; j--) {
            if (checkBit(block0, i, j) !== 0) {
                z = exclusiveOR(z, v);
            }
            if (checkBit(v, 15, 0) !== 0) {
                v = exclusiveOR(rightShift(v), R);
            }
            else {
                v = rightShift(v);
            }
        }
    }
    return z;
}

See also: checkBit, exclusiveOR, rightShift

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: rightShift

rightShift = function (block: number[]): number[] {
    let i: number;
    let carry = 0;
    let oldCarry = 0;
    for (i = 0; i < block.length; i++) {
        oldCarry = carry;
        carry = block[i] & 1;
        block[i] = block[i] >> 1;
        if (oldCarry !== 0) {
            block[i] = block[i] | 128;
        }
    }
    return block;
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: ripemd160

ripemd160 = (msg: number[] | string, enc?: "hex" | "utf8"): number[] => {
    return new RIPEMD160().update(msg, enc).digest();
}

See also: RIPEMD160

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: sha1

sha1 = (msg: number[] | string, enc?: "hex" | "utf8"): number[] => {
    return new SHA1().update(msg, enc).digest();
}

See also: SHA1

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: sha256

sha256 = (msg: number[] | string, enc?: "hex" | "utf8"): number[] => {
    return new SHA256().update(msg, enc).digest();
}

See also: SHA256

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: sha256hmac

sha256hmac = (key: number[] | string, msg: number[] | string, enc?: "hex"): number[] => {
    return new SHA256HMAC(key).update(msg, enc).digest();
}

See also: SHA256HMAC

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: sha512

sha512 = (msg: number[] | string, enc?: "hex" | "utf8"): number[] => {
    return new SHA512().update(msg, enc).digest();
}

See also: SHA512

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: sha512hmac

sha512hmac = (key: number[] | string, msg: number[] | string, enc?: "hex"): number[] => {
    return new SHA512HMAC(key).update(msg, enc).digest();
}

See also: SHA512HMAC

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: sign

sign = (msg: BigNumber, key: BigNumber, forceLowS: boolean = false, customK?: BigNumber | ((iter: number) => BigNumber)): Signature => {
    if (typeof BigInt === "function") {
        const zero = BigInt(0);
        const one = BigInt(1);
        const two = BigInt(2);
        const n = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
        const p = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");
        const Gx = BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798");
        const Gy = BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8");
        const G = { x: Gx, y: Gy };
        const z = BigInt("0x" + msg.toString(16));
        const d = BigInt("0x" + key.toString(16));
        if (d <= zero || d >= n) {
            throw new Error("Invalid private key");
        }
        function bigIntToBytes(value: bigint, length: number): Uint8Array {
            const hex = value.toString(16).padStart(length * 2, "0");
            const bytes = new Uint8Array(length);
            for (let i = 0; i < length; i++) {
                bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
            }
            return bytes;
        }
        const bytes = 32;
        const bkey = bigIntToBytes(d, bytes);
        const nonce = bigIntToBytes(z, bytes);
        const drbg = new DRBG(Array.from(bkey), Array.from(nonce));
        const ns1 = n - one;
        let iter = 0;
        function truncateToN(k: bigint, n: bigint, truncOnly: boolean = true): bigint {
            const kBitLength = k.toString(2).length;
            const nBitLength = n.toString(2).length;
            const delta = kBitLength - nBitLength;
            if (delta > 0) {
                k = k >> BigInt(delta);
            }
            if (!truncOnly && k >= n) {
                return k - n;
            }
            else {
                return k;
            }
        }
        function generateK(customK?: BigNumber | ((iter: number) => BigNumber)): bigint {
            if (typeof customK === "function") {
                const kbn = customK(iter);
                const kstr = kbn.toString(16);
                return BigInt("0x" + kstr);
            }
            else if ((customK != null) && BigNumber.isBN(customK)) {
                const kstr = customK.toString(16);
                return BigInt("0x" + kstr);
            }
            else {
                const khex = drbg.generate(bytes);
                return BigInt("0x" + khex);
            }
        }
        function mod(a: bigint, m: bigint): bigint {
            return ((a % m) + m) % m;
        }
        function modInv(a: bigint, m: bigint): bigint {
            let lm = one;
            let hm = zero;
            let low = mod(a, m);
            let high = m;
            while (low > one) {
                const r = high / low;
                const nm = hm - lm * r;
                const neww = high - low * r;
                hm = lm;
                lm = nm;
                high = low;
                low = neww;
            }
            return mod(lm, m);
        }
        function pointAdd(P: {
            x: bigint;
            y: bigint;
        } | null, Q: {
            x: bigint;
            y: bigint;
        } | null): {
            x: bigint;
            y: bigint;
        } | null {
            if (P === null)
                return Q;
            if (Q === null)
                return P;
            if (P.x === Q.x && P.y === mod(-Q.y, p)) {
                return null;
            }
            let m: bigint;
            if (P.x === Q.x && P.y === Q.y) {
                if (P.y === zero) {
                    return null;
                }
                const numerator = mod(BigInt(3) * P.x * P.x, p);
                const denominator = modInv(two * P.y, p);
                m = mod(numerator * denominator, p);
            }
            else {
                const numerator = mod(Q.y - P.y, p);
                const denominator = modInv(Q.x - P.x, p);
                m = mod(numerator * denominator, p);
            }
            const xR = mod(m * m - P.x - Q.x, p);
            const yR = mod(m * (P.x - xR) - P.y, p);
            return { x: xR, y: yR };
        }
        function scalarMul(k: bigint, P: {
            x: bigint;
            y: bigint;
        }): {
            x: bigint;
            y: bigint;
        } {
            let N = P;
            let Q: {
                x: bigint;
                y: bigint;
            } | null = null;
            while (k > BigInt(0)) {
                if (k % BigInt(2) === BigInt(1)) {
                    Q = Q === null ? N : (pointAdd(Q, N) ?? Q);
                }
                N = pointAdd(N, N) ?? N;
                k >>= BigInt(1);
            }
            if (Q === null) {
                throw new Error("Scalar multiplication resulted in an invalid point.");
            }
            return Q;
        }
        let validSignature = false;
        while (!validSignature) {
            iter += 1;
            validSignature = true;
            iter += 1;
            let k = generateK(customK);
            k = truncateToN(k, n, true);
            if (k <= one || k >= ns1) {
                if (customK instanceof BigNumber) {
                    throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");
                }
                else {
                    continue;
                }
            }
            const R = scalarMul(k, G);
            if (R === null) {
                if (customK instanceof BigNumber) {
                    throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");
                }
                else {
                    continue;
                }
            }
            const r = mod(R.x, n);
            if (r === zero) {
                if (customK instanceof BigNumber) {
                    throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");
                }
                else {
                    continue;
                }
            }
            const kInv = modInv(k, n);
            const rd = mod(r * d, n);
            let s = mod(kInv * (z + rd), n);
            if (s === zero) {
                if (customK instanceof BigNumber) {
                    throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)");
                }
                else {
                    continue;
                }
            }
            if (forceLowS && s > n / two) {
                s = n - s;
            }
            const rbn = new BigNumber(r.toString(16), 16);
            const sbn = new BigNumber(s.toString(16), 16);
            return new Signature(rbn, sbn);
        }
    }
    else {
        const curve = new Curve();
        msg = truncateToN(msg);
        const bytes = curve.n.byteLength();
        const bkey = key.toArray("be", bytes);
        const nonce = msg.toArray("be", bytes);
        const drbg = new DRBG(bkey, nonce);
        const ns1 = curve.n.subn(1);
        for (let iter = 0;; iter++) {
            let k = typeof customK === "function"
                ? customK(iter)
                : BigNumber.isBN(customK)
                    ? customK
                    : new BigNumber(drbg.generate(bytes), 16);
            if (k != null) {
                k = truncateToN(k, true);
            }
            else {
                throw new Error("k is undefined");
            }
            if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) {
                if (BigNumber.isBN(customK)) {
                    throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");
                }
                else {
                    continue;
                }
            }
            const kp = curve.g.mul(k);
            if (kp.isInfinity()) {
                if (BigNumber.isBN(customK)) {
                    throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");
                }
                else {
                    continue;
                }
            }
            const kpX = kp.getX();
            const r = kpX.umod(curve.n);
            if (r.cmpn(0) === 0) {
                if (BigNumber.isBN(customK)) {
                    throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");
                }
                else {
                    continue;
                }
            }
            let s = k.invm(curve.n).mul(r.mul(key).iadd(msg));
            s = s.umod(curve.n);
            if (s.cmpn(0) === 0) {
                if (BigNumber.isBN(customK)) {
                    throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)");
                }
                else {
                    continue;
                }
            }
            if (forceLowS && s.cmp(curve.n.ushrn(1)) > 0) {
                s = curve.n.sub(s);
            }
            return new Signature(r, s);
        }
    }
    throw new Error("Failed to generate a valid signature");
}

See also: BigNumber, Curve, DRBG, Signature, toArray

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: toArray

toArray = (msg: any, enc?: "hex" | "utf8" | "base64"): any[] => {
    if (Array.isArray(msg))
        return msg.slice();
    if (msg === undefined)
        return [];
    if (typeof msg !== "string") {
        return Array.from(msg, (item: any) => item | 0);
    }
    switch (enc) {
        case "hex":
            return hexToArray(msg);
        case "base64":
            return base64ToArray(msg);
        default:
            return utf8ToArray(msg);
    }
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: toBase58

toBase58 = (bin: number[]): string => {
    const base58Map = Array(256).fill(-1);
    for (let i = 0; i < base58chars.length; ++i) {
        base58Map[base58chars.charCodeAt(i)] = i;
    }
    const result: number[] = [];
    for (const byte of bin) {
        let carry = byte;
        for (let j = 0; j < result.length; ++j) {
            const x = (base58Map[result[j]] << 8) + carry;
            result[j] = base58chars.charCodeAt(x % 58);
            carry = (x / 58) | 0;
        }
        while (carry !== 0) {
            result.push(base58chars.charCodeAt(carry % 58));
            carry = (carry / 58) | 0;
        }
    }
    for (const byte of bin) {
        if (byte !== 0)
            break;
        else
            result.push("1".charCodeAt(0));
    }
    result.reverse();
    return String.fromCharCode(...result);
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: toBase58Check

toBase58Check = (bin: number[], prefix: number[] = [0]): string => {
    let hash = hash256([...prefix, ...bin]);
    hash = [...prefix, ...bin, ...hash.slice(0, 4)];
    return toBase58(hash);
}

See also: hash256, toBase58

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: toHex

toHex = (msg: number[]): string => {
    let res = "";
    for (const num of msg) {
        res += zero2(num.toString(16));
    }
    return res;
}

See also: zero2

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: toUTF8

toUTF8 = (arr: number[]): string => {
    let result = "";
    let skip = 0;
    for (let i = 0; i < arr.length; i++) {
        const byte = arr[i];
        if (skip > 0) {
            skip--;
            continue;
        }
        if (byte <= 127) {
            result += String.fromCharCode(byte);
        }
        else if (byte >= 192 && byte <= 223) {
            const byte2 = arr[i + 1];
            skip = 1;
            const codePoint = ((byte & 31) << 6) | (byte2 & 63);
            result += String.fromCharCode(codePoint);
        }
        else if (byte >= 224 && byte <= 239) {
            const byte2 = arr[i + 1];
            const byte3 = arr[i + 2];
            skip = 2;
            const codePoint = ((byte & 15) << 12) | ((byte2 & 63) << 6) | (byte3 & 63);
            result += String.fromCharCode(codePoint);
        }
        else if (byte >= 240 && byte <= 247) {
            const byte2 = arr[i + 1];
            const byte3 = arr[i + 2];
            const byte4 = arr[i + 3];
            skip = 3;
            const codePoint = ((byte & 7) << 18) |
                ((byte2 & 63) << 12) |
                ((byte3 & 63) << 6) |
                (byte4 & 63);
            const surrogate1 = 55296 + ((codePoint - 65536) >> 10);
            const surrogate2 = 56320 + ((codePoint - 65536) & 1023);
            result += String.fromCharCode(surrogate1, surrogate2);
        }
    }
    return result;
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: verify

verify = (msg: BigNumber, sig: Signature, key: Point): boolean => {
    if (typeof BigInt === "function") {
        const zero = BigInt(0);
        const one = BigInt(1);
        const two = BigInt(2);
        const three = BigInt(3);
        const p = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");
        const n = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
        const G = {
            x: BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),
            y: BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")
        };
        const mod = (a: bigint, m: bigint): bigint => ((a % m) + m) % m;
        const modInv = (a: bigint, m: bigint): bigint => {
            let [oldr, r] = [a, m];
            let [olds, s] = [BigInt(1), BigInt(0)];
            while (r !== zero) {
                const q = oldr / r;
                [oldr, r] = [r, oldr - q * r];
                [olds, s] = [s, olds - q * s];
            }
            if (oldr > one)
                return zero;
            return mod(olds, m);
        };
        const modMul = (a: bigint, b: bigint, m: bigint): bigint => mod(a * b, m);
        const modSub = (a: bigint, b: bigint, m: bigint): bigint => mod(a - b, m);
        const four = BigInt(4);
        const eight = BigInt(8);
        interface JacobianPoint {
            X: bigint;
            Y: bigint;
            Z: bigint;
        }
        const pointDouble = (P: JacobianPoint): JacobianPoint => {
            const { X: X1, Y: Y1, Z: Z1 } = P;
            if (Y1 === zero) {
                return { X: zero, Y: one, Z: zero };
            }
            const Y1sq = modMul(Y1, Y1, p);
            const S = modMul(four, modMul(X1, Y1sq, p), p);
            const M = modMul(three, modMul(X1, X1, p), p);
            const X3 = modSub(modMul(M, M, p), modMul(two, S, p), p);
            const Y3 = modSub(modMul(M, modSub(S, X3, p), p), modMul(eight, modMul(Y1sq, Y1sq, p), p), p);
            const Z3 = modMul(two, modMul(Y1, Z1, p), p);
            return { X: X3, Y: Y3, Z: Z3 };
        };
        const pointAdd = (P: JacobianPoint, Q: JacobianPoint): JacobianPoint => {
            if (P.Z === zero)
                return Q;
            if (Q.Z === zero)
                return P;
            const Z1Z1 = modMul(P.Z, P.Z, p);
            const Z2Z2 = modMul(Q.Z, Q.Z, p);
            const U1 = modMul(P.X, Z2Z2, p);
            const U2 = modMul(Q.X, Z1Z1, p);
            const S1 = modMul(P.Y, modMul(Z2Z2, Q.Z, p), p);
            const S2 = modMul(Q.Y, modMul(Z1Z1, P.Z, p), p);
            const H = modSub(U2, U1, p);
            const r = modSub(S2, S1, p);
            if (H === zero) {
                if (r === zero) {
                    return pointDouble(P);
                }
                else {
                    return { X: zero, Y: one, Z: zero };
                }
            }
            const HH = modMul(H, H, p);
            const HHH = modMul(H, HH, p);
            const V = modMul(U1, HH, p);
            const X3 = modSub(modSub(modMul(r, r, p), HHH, p), modMul(two, V, p), p);
            const Y3 = modSub(modMul(r, modSub(V, X3, p), p), modMul(S1, HHH, p), p);
            const Z3 = modMul(H, modMul(P.Z, Q.Z, p), p);
            return { X: X3, Y: Y3, Z: Z3 };
        };
        const scalarMultiply = (k: bigint, P: {
            x: bigint;
            y: bigint;
        }): JacobianPoint => {
            const N: JacobianPoint = { X: P.x, Y: P.y, Z: one };
            let Q: JacobianPoint = { X: zero, Y: one, Z: zero };
            const kBin = k.toString(2);
            for (let i = 0; i < kBin.length; i++) {
                Q = pointDouble(Q);
                if (kBin[i] === "1") {
                    Q = pointAdd(Q, N);
                }
            }
            return Q;
        };
        const verifyECDSA = (hash: bigint, publicKey: {
            x: bigint;
            y: bigint;
        }, signature: {
            r: bigint;
            s: bigint;
        }): boolean => {
            const { r, s } = signature;
            const z = hash;
            if (r <= zero || r >= n || s <= zero || s >= n) {
                return false;
            }
            const w = modInv(s, n);
            if (w === zero) {
                return false;
            }
            const u1 = modMul(z, w, n);
            const u2 = modMul(r, w, n);
            const RG = scalarMultiply(u1, G);
            const RQ = scalarMultiply(u2, publicKey);
            const R = pointAdd(RG, RQ);
            if (R.Z === zero) {
                return false;
            }
            const ZInv = modInv(R.Z, p);
            if (ZInv === zero) {
                return false;
            }
            const ZInv2 = modMul(ZInv, ZInv, p);
            const x1affine = modMul(R.X, ZInv2, p);
            const v = mod(x1affine, n);
            return v === r;
        };
        const hash = BigInt("0x" + msg.toString(16));
        if ((key.x == null) || (key.y == null)) {
            throw new Error("Invalid public key: missing coordinates.");
        }
        const publicKey = {
            x: BigInt("0x" + key.x.toString(16)),
            y: BigInt("0x" + key.y.toString(16))
        };
        const signature = {
            r: BigInt("0x" + sig.r.toString(16)),
            s: BigInt("0x" + sig.s.toString(16))
        };
        return verifyECDSA(hash, publicKey, signature);
    }
    else {
        const curve = new Curve();
        msg = truncateToN(msg);
        const r = sig.r;
        const s = sig.s;
        if (r.cmpn(1) < 0 || r.cmp(curve.n) >= 0) {
            return false;
        }
        if (s.cmpn(1) < 0 || s.cmp(curve.n) >= 0) {
            return false;
        }
        const sinv = s.invm(curve.n);
        const u1 = sinv.mul(msg).umod(curve.n);
        const u2 = sinv.mul(r).umod(curve.n);
        const p = curve.g.jmulAdd(u1, key, u2);
        if (p.isInfinity()) {
            return false;
        }
        return p.eqXToP(r);
    }
}

See also: BigNumber, Curve, JacobianPoint, Point, Signature

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables


Variable: zero2

zero2 = (word: string): string => {
    if (word.length % 2 === 1) {
        return "0" + word;
    }
    else {
        return word;
    }
}

Links: API, Interfaces, Classes, Functions, Types, Enums, Variables