libnexa-ts
Version:
A pure and powerful Nexa SDK library.
1,559 lines (1,501 loc) • 103 kB
TypeScript
import { BNInput } from 'elliptic';
import { curve } from 'elliptic';
import { default as default_2 } from 'bn.js';
export declare class Address {
readonly data: Uint8Array;
readonly network: Network;
readonly type: AddressType;
/**
* Instantiate an address from an address String or Uint8Array, a public key or script hash Uint8Array,
* or an instance of {@link PublicKey} or {@link Script}.
*
* This is an immutable class, and if the first parameter provided to this constructor is an
* `Address` instance, the same argument will be returned.
*
* An address has two key properties: `network` and `type`. The type is either
* `AddressType.PayToPublicKeyHash` (value is the `'P2PKH'` string)
* or `AddressType.PayToScriptTemplate` (the string `'P2ST'`). The network is an instance of {@link Network} or network name.
* You can quickly check whether an address is of a given kind by using the methods
* `isPayToPublicKeyHash` and `isPayToScriptTemplate`
*
* @example
* ```javascript
* // validate that an input field is valid
* let error = Address.getValidationError(input, 'testnet');
* if (!error) {
* let address = new Address(input, 'testnet');
* } else {
* // invalid network or checksum (typo?)
* let message = error.messsage;
* }
*
* // get an address from a public key
* let address = Address.fromPublicKey(publicKey, 'testnet').toString();
* ```
*
* @param data The encoded data in various formats
* @param network The network: 'mainnet' (default) or 'testnet'
* @param type The type of address: 'P2ST' (default) or 'P2PKH' or 'GROUP'
* @returns A new valid and frozen instance of an Address
*/
constructor(data: Address | string | Uint8Array, network?: Networkish, type?: AddressType);
static validateParams(network?: Networkish, type?: AddressType): void;
/**
* @param address string
*
* @returns A new valid and frozen instance of an Address
*/
static fromString(address: string): Address;
/**
* Will return a cashaddr representation of the address. Always return lower case
* Can be converted by the caller to uppercase is needed (still valid).
*
* @returns Nexa address
*/
toString(): string;
/**
* Will return a string formatted for the console
*
* @returns {string} Bitcoin address
*/
inspect(): string;
/**
* Instantiate an address from an Object
*
* @param obj - A JSON object with keys: data, network and type
* @returns A new valid instance of an Address
*/
static fromObject(obj: AddressDto): Address;
/**
* @returns A plain object with the address information
*/
toJSON(): AddressDto;
toObject: () => AddressDto;
/**
* @return true if an address is of pay to public key hash type
*/
isPayToPublicKeyHash(): boolean;
/**
* @return true if an address is of pay to script template type
*/
isPayToScriptTemplate(): boolean;
/**
* @return true if an address is a group token address
*/
isGroupIdentifierAddress(): boolean;
/**
* Will return a validation error if exists
*
* @example
* ```javascript
* // a network mismatch error
* let error = Address.getValidationError('nexatest:nqtsq5g567x44x5g54t2wsxz60zwqmyks63rkrddl4stwnzu', 'testnet');
* ```
*
* @param data The encoded data
* @param network either a Network instance, 'mainnet', or 'testnet'
* @param type The type of address: 'P2ST' or 'GROUP' or 'P2PKH'
* @returns The corresponding error message
*/
static getValidationError(data: string | Uint8Array, network?: Networkish, type?: AddressType): Error | undefined;
/**
* Will return a boolean if an address is valid
*
* @example
* ```javascript
* assert(Address.isValid('nexa:nqtsq5g567x44x5g54t2wsxz60zwqmyks63rkrddsfq94pd2', 'mainned'));
* ```
*
* @param data The encoded data
* @param network either a Network instance, 'mainnet', or 'testnet'
* @param type The type of address: 'P2ST' or 'GROUP' or 'P2PKH'
* @returns true if valid
*/
static isValid(data: string | Uint8Array, network?: Networkish, type?: AddressType): boolean;
/**
* Instantiate an address from a PublicKey instance
*
* @param pubkey the public key instance
* @param network either a Network instance, 'mainnet' or 'testnet'
* @param type address encoding type
* @returns A new valid and frozen instance of an Address
*/
static fromPublicKey(pubkey: PublicKey, network?: Networkish, type?: AddressType): Address;
/**
* Instantiate an address from a non grouped script template
*
* @param templateHash An instance of a template hash Uint8Array
* @param constraintHash An instance of a constraint hash Uint8Array
* @param visibleArgs An array of push-only args, or hex string represent script buffer, or Script with push args
* @param network either a Network instance, 'mainnet' or 'testnet'
* @returns A new valid and frozen instance of an Address
*/
static fromScriptTemplate(templateHash: Uint8Array | Opcode, constraintHash: Uint8Array | Opcode, visibleArgs?: string | Script | ScriptElement[], network?: Networkish): Address;
/**
* Internal function to transform a {@link PublicKey}
*/
private static _transformPublicKey;
/**
* Internal function to transform a Script Template params
*/
private static _transformScriptTemplate;
/**
* Will return the transaction output type by the address type
*
* @param address as string
* @returns 1 - Template, 0 - otherwise
*/
static getOutputType(address: string): number;
/**
* Will return the transaction output type by the address type
*
* @returns 1 - Template, 0 - otherwise
*/
getOutputType(): number;
}
export declare interface AddressDto {
data: string;
network: string;
type: string;
}
export declare enum AddressType {
PayToPublicKeyHash = "P2PKH",
PayToScriptTemplate = "P2ST",
GroupIdAddress = "GROUP"
}
/**
* Any type that can be used where a big number is needed.
*/
export declare type BigNumberish = string | Numeric;
export declare class Block implements IBlock {
header: BlockHeader;
transactions: Transaction[];
constructor(data: Uint8Array | IBlock);
get hash(): string;
/**
* @param obj A plain JavaScript object
* @returns An instance of block
*/
static fromObject(obj: IBlock): Block;
/**
* @param br A BufferReader of the block
* @returns An object representing the block data
*/
private static _fromBufferReader;
/**
* @param br A buffer reader of the block
* @returns An instance of block
*/
static fromBufferReader(br: BufferReader): Block;
/**
* @param buf A buffer of the block
* @returns An instance of block
*/
static fromBuffer(buf: Uint8Array): Block;
/**
* @param str A hex encoded string of the block
* @returns A hex encoded string of the block
*/
static fromString(str: string): Block;
toJSON: () => IBlock;
/**
* @returns A plain object with the block properties
*/
toObject(): IBlock;
/**
* @param bw An existing instance of BufferWriter (optional)
* @returns An instance of BufferWriter representation of the Block
*/
toBufferWriter(bw?: BufferWriter): BufferWriter;
/**
* @returns A buffer of the block
*/
toBuffer(): Uint8Array;
/**
* @returns A hex encoded string of the block
*/
toString(): string;
/**
* @returns A string formatted for the console
*/
inspect(): string;
/**
* Will iterate through each transaction and return an array of hashes
* @returns An array with transaction hashes
*/
getTransactionHashes(): Uint8Array[];
/**
* Will build a merkle tree of all the transactions, ultimately arriving at
* a single point, the merkle root.
*
* @see {@link https://spec.nexa.org/blocks/merkle-tree/}
* @returns An array with each level of the tree after the other.
*/
getMerkleTree(): Uint8Array[];
/**
* Calculates the merkleRoot from the transactions.
*
* @returns A buffer of the merkle root hash
*/
getMerkleRoot(): Uint8Array;
/**
* Verifies that the transactions in the block match the header merkle root
*
* @returns true If the merkle roots match
*/
validMerkleRoot(): boolean;
}
export declare class BlockHeader implements IBlockHeader {
static readonly MAX_TIME_OFFSET: number;
prevHash: Uint8Array;
bits: number;
ancestorHash: Uint8Array;
merkleRoot: Uint8Array;
txFilter: Uint8Array;
time: number;
height: number;
chainWork: Uint8Array;
size: number;
txCount: number;
poolFee: number;
utxoCommitment: Uint8Array;
minerData: Uint8Array;
nonce: Uint8Array;
constructor(data: Uint8Array | IBlockHeader);
get hash(): string;
/**
* @returns The little endian hash buffer of the header
*/
private _getHash;
/**
* @param br A BufferReader of the block header
* @returns An object representing block header data
*/
private static _fromBufferReader;
/**
* This method is useful for hex that represent concatination of multiple headers
* so it able to serve in a loop.
*
* @param br A BufferReader of the block header
* @returns An instance of block header
*/
static fromBufferReader(br: BufferReader): BlockHeader;
/**
* @param header A plain JavaScript block header object
* @returns An instance of block header
*/
static fromObject(header: IBlockHeader): BlockHeader;
/**
* @param buf A buffer of the block header
* @returns An instance of block header
*/
static fromBuffer(buf: Uint8Array): BlockHeader;
/**
* @param hex A hex encoded buffer of the block header
* @returns An instance of block header
*/
static fromString(hex: string): BlockHeader;
toJSON: () => IBlockHeader;
/**
* @returns A plain object of the BlockHeader
*/
toObject(): IBlockHeader;
/**
* @param bw - An existing instance BufferWriter
* @returns An instance of BufferWriter representation of the BlockHeader
*/
toBufferWriter(bw?: BufferWriter): BufferWriter;
/**
* @returns A Uint8Array of the BlockHeader
*/
toBuffer(): Uint8Array;
/**
* @returns A hex encoded string of the BlockHeader
*/
toString(): string;
/**
* @returns A string formatted for the console
*/
inspect(): string;
/**
* Returns the target difficulty for this block
*
* @param bits the bits number
* @returns An instance of BN with the decoded difficulty bits
*/
getTargetDifficulty(bits?: number): BNExtended;
/**
* @returns the target difficulty for this block
*/
getDifficulty(): number;
/**
* @returns true If timestamp is not too far in the future
*/
validTimestamp(): boolean;
}
export declare class BNExtended extends default_2 {
static Zero: BNExtended;
static One: BNExtended;
static Minus1: BNExtended;
static fromNumber(num: number): BNExtended;
static fromBigInt(num: bigint): BNExtended;
static fromString(str: string, base?: number | "hex"): BNExtended;
static fromBuffer(buf: Uint8Array, opts?: BNOptions): BNExtended;
/**
* Create a BN from a "ScriptNum":
* This is analogous to the constructor for CScriptNum in nexad. Many ops in
* nexad's script interpreter use CScriptNum, which is not really a proper
* bignum. Instead, an error is thrown if trying to input a number bigger than
* 4 bytes. We copy that behavior here. A third argument, `size`, is provided to
* extend the hard limit of 4 bytes, as some usages require more than 4 bytes.
*/
static fromScriptNumBuffer(buf: Uint8Array, fRequireMinimal?: boolean, size?: number): BNExtended;
add(b: default_2): BNExtended;
sub(b: default_2): BNExtended;
mul(b: default_2): BNExtended;
mod(b: default_2): BNExtended;
umod(b: default_2): BNExtended;
invm(b: default_2): BNExtended;
neg(): BNExtended;
toNumber(): number;
toBigInt(): bigint;
toByteArray(opts?: default_2.Endianness | BNOptions, length?: number): Uint8Array;
/**
* The corollary to the above, with the notable exception that we do not throw
* an error if the output is larger than four bytes. (Which can happen if
* performing a numerical operation that results in an overflow to more than 4
* bytes).
*/
toScriptNumBuffer(): Uint8Array;
toScriptBigNumBuffer(): Uint8Array;
getSize(): number;
safeAdd(bigNumToAdd: BNExtended, maxSize: number): BNExtended;
safeSub(bigNumToSubtract: BNExtended, maxSize: number): BNExtended;
safeMul(bigNumToMultiply: BNExtended, maxSize: number): BNExtended;
private checkOperationForOverflow;
private toSMBigEndian;
private toBigNumSMBigEndian;
private toSM;
/**
* Instantiate a BigNumber from a "signed magnitude buffer"
* (a buffer where the most significant bit represents the sign (0 = positive, -1 = negative))
*/
private static fromSM;
private static trim;
private static pad;
}
export declare interface BNOptions {
endian?: "little" | "big";
size?: number;
bignum?: boolean;
}
export declare interface BufferParams {
buf?: Uint8Array;
pos?: number;
}
export declare class BufferReader {
buf: Uint8Array;
pos: number;
constructor(buf?: Uint8Array | string | BufferParams);
set(obj: BufferParams): this;
eof(): boolean;
finished: () => boolean;
read(len: number): Uint8Array;
readAll(): Uint8Array;
readUInt8(): number;
readUInt16BE(): number;
readUInt16LE(): number;
readUInt32BE(): number;
readUInt32LE(): number;
readInt32LE(): number;
readUInt64BEBN(): BNExtended;
readUInt64LEBN(): BNExtended;
readVarintNum(): number;
/**
* reads a length prepended buffer
*/
readVarLengthBuffer(): Uint8Array;
readVarintBuf(): Uint8Array;
readVarintBN(): BNExtended;
reverse(): this;
readReverse(len?: number): Uint8Array;
readCoreVarintNum(): number;
}
export declare class BufferUtils {
/**
* Tests for both node's Buffer and Uint8Array
*
* @param arg
* @return Returns true if the given argument is an instance of a Uint8Array.
*/
static isBuffer(arg: unknown): arg is Uint8Array;
/**
* Tests for both node's Buffer and Uint8Array
*
* @param arg
* @return Returns true if the given argument is an instance of a hash160 or hash256 buffer.
*/
static isHashBuffer(arg: unknown): boolean;
/**
* Reverse a Uint8Array
* @param param
* @return new reversed Uint8Array
*/
static reverse(param: Uint8Array): Uint8Array;
/**
* Convert a Uint8Array to a UTF-8 string.
*
* @param buffer - Uint8Array containing UTF-8 encoded bytes
* @returns Decoded string
*/
static bufferToUtf8(buffer: Uint8Array): string;
/**
* Convert a UTF-8 string to a Uint8Array.
*
* @param str - UTF-8 string
* @returns Encoded Uint8Array
*/
static utf8ToBuffer(str: string): Uint8Array;
/**
* Convert a Uint8Array to a Base64 string.
*
* @param buffer - Uint8Array containing Base64 encoded bytes
* @returns Decoded string
*/
static bufferToBase64(buffer: Uint8Array): string;
/**
* Convert a Base64 string to a Uint8Array.
*
* @param str - Base64 string
* @returns Encoded Uint8Array
*/
static base64ToBuffer(str: string): Uint8Array;
/**
* Transforms a buffer into a string with a number in hexa representation
*
* Similar for <tt>buffer.toString('hex')</tt>
*
* @param buffer
* @return string
*/
static bufferToHex(buffer: Uint8Array): string;
/**
* Convert a hexadecimal string into a Uint8Array.
*
* @param hex - Hex string (must have even length)
* @returns Uint8Array representing the bytes
*/
static hexToBuffer(hex: string): Uint8Array;
/**
* Concatenate multiple Uint8Arrays into a single Uint8Array.
*
* Mimics Node.js Buffer.concat(list, totalLength?):
* - list: Array of Uint8Arrays
* - totalLength: Optional precomputed total length
*
* @param list - Array of Uint8Arrays to concatenate
* @param totalLength - Optional total length to preallocate
* @returns New Uint8Array containing all bytes from input arrays
*
* @example
* const a = new Uint8Array([1,2]);
* const b = new Uint8Array([3,4]);
* const result = Uint8ArrayUtils.concat([a,b]);
* console.log(result); // Uint8Array(4) [1,2,3,4]
*/
static concat(list: Uint8Array[], totalLength?: number): Uint8Array;
/**
* Compares two Uint8Arrays for byte-wise equality.
*
* This function checks whether the two arrays have the same length
* and the same content.
*
* @param a - The first Uint8Array to compare.
* @param b - The second Uint8Array to compare.
* @returns `true` if the arrays have the same length and contents, `false` otherwise.
*/
static equals(a: Uint8Array, b: Uint8Array): boolean;
/**
* Transforms a number from 0 to 255 into a Uint8Array of size 1 with that value
*
* @param integer
* @return Uint8Array
*/
static integerAsSingleByteBuffer(integer: number): Uint8Array;
/**
* Transforms the first byte of an array into a number ranging from -128 to 127
*
* @param buffer
* @return number
*/
static integerFromSingleByteBuffer(buffer: Uint8Array): number;
/**
* Transform a 4-byte integer into a Uint8Array of length 4.
*
* @param integer
* @return Uint8Array
*/
static integerAsBuffer(integer: number): Uint8Array;
/**
* Transform the first 4 values of a Uint8Array into a number, in little endian encoding
*
* @param buffer
* @return integer
*/
static integerFromBuffer(buffer: Uint8Array): number;
/**
* @return secure random bytes
*/
static getRandomBuffer(size: number): Uint8Array;
}
export declare class BufferWriter {
private bufs;
private bufLen;
constructor(obj?: BufferWriterOptions);
set(obj: BufferWriterOptions): this;
toBuffer(): Uint8Array;
concat(): Uint8Array;
write(buf: Uint8Array): this;
writeReverse(buf: Uint8Array): this;
writeUInt8(n: number): this;
writeUInt16BE(n: number): this;
writeUInt16LE(n: number): this;
writeUInt32BE(n: number): this;
writeInt32LE(n: number): this;
writeUInt32LE(n: number): this;
writeUInt64BEBN(bn: BNExtended): this;
writeUInt64LEBN(bn: BNExtended): this;
writeVarintNum(n: number): this;
writeVarintBN(bn: BNExtended): this;
writeVarLengthBuf(buf: Uint8Array): this;
writeCoreVarintNum(n: number): this;
static varintBufNum(n: number): Uint8Array;
static varintBufBN(bn: BNExtended): Uint8Array;
}
export declare interface BufferWriterOptions {
bufs?: Uint8Array[];
}
export declare class CommonUtils {
/**
* Determines whether a string contains only hexadecimal values
*
* @param value
* @returns true if the string is the hexa representation of a number
*/
static isHexa(value: unknown): boolean;
/**
* Test if an argument is a valid JSON object. If it is, returns a truthy
* value (the json object decoded), so no double JSON.parse call is necessary
*
* @param arg
* @return false if the argument is not a JSON string.
*/
static isValidJSON(arg: string): object | boolean;
/**
* Checks that a value is a natural number.
*
* @param value
* @return true if a positive integer or zero.
*/
static isNaturalNumber(value: number): boolean;
/**
* Checks that a value is a natural number.
*
* @param value
* @return true if a positive integer or zero.
*/
static isNaturalBigInt(value: bigint): boolean;
}
export declare abstract class DigitalSignature implements IDigitalSignature {
hashbuf: Uint8Array;
endian?: EndianType;
privkey: IPrivateKey;
pubkey: IPublicKey;
sig?: ISignature;
verified?: boolean;
constructor(obj?: Partial<IDigitalSignature>);
protected set(obj: Partial<IDigitalSignature>): this;
protected abstract _findSignature(d: BNExtended, e: BNExtended): Partial<ISignature>;
abstract sigError(): boolean | string;
sign(): this;
verify(): this;
toPublicKey(): IPublicKey;
privkey2pubkey(): void;
}
/**
* IMPORTANT: ECDSA only used for compact message signing.
* for transactions signing, use Schnorr.
*/
export declare class ECDSA extends DigitalSignature {
k?: BNExtended;
set(obj: Partial<ECDSA>): this;
sigError(): boolean | string;
protected _findSignature(d: BNExtended, e: BNExtended): Partial<ISignature>;
private static toLowS;
calcI(): this;
randomK(): this;
deterministicK(badrs?: number): this;
signRandomK(): this;
toString(): string;
toPublicKey(): PublicKey;
static fromString(str: string): ECDSA;
static sign(hashbuf: Uint8Array, privkey: IPrivateKey, endian?: EndianType): ISignature;
static verify(hashbuf: Uint8Array, sig: ISignature, pubkey: IPublicKey, endian?: EndianType): boolean;
}
export declare type EndianType = "big" | "little";
export declare interface GroupIdData {
hashBuffer: Uint8Array;
nonce: bigint;
}
export declare enum GroupIdFlag {
NONE = 0,
COVENANT = 1,// covenants/encumberances -- output script template must match input
HOLDS_NEX = 2,// group inputs and outputs must balance NEX, token quantity MUST be 0
GROUP_RESERVED_BITS = 65532,
DEFAULT = 0
}
/**
* Represent Group creation id type in OP_RETURN script
*/
export declare enum GroupIdType {
/** Legacy token */
LEGACY = 88888888,
/** Token */
NRC1 = 88888890,
/** NFT Collection */
NRC2 = 88888891,
/** NFT that belongs to a collection */
NRC3 = 88888892
}
/**
* A util class with methods for group tokenization.
*/
export declare class GroupToken {
static readonly PARENT_GROUP_ID_SIZE = 32;
static readonly authFlags: {
/** Has all permissions */
ACTIVE_FLAG_BITS: bigint;
RESERVED_FLAG_BITS: bigint;
/** Is this a controller utxo (forces negative number in amount) */
AUTHORITY: bigint;
/** Can mint tokens */
MINT: bigint;
/** Can melt tokens */
MELT: bigint;
/** Can create authorities */
BATON: bigint;
/** Can change the redeem script */
RESCRIPT: bigint;
/** Can create subgroups */
SUBGROUP: bigint;
NONE: bigint;
ALL_FLAG_BITS: bigint;
};
/**
* Calculate a group ID based on the provided inputs. Pass 'null' to opReturnScript if there is not
* going to be an OP_RETURN output in the transaction.
*
* @param outpoint The input outpoint hash hex or buffer
* @param opReturnScript opReturn output script
* @param authFlag group authority flag (use {@link GroupToken.authFlags})
* @param idFlag group id flag
*
* @returns Object with group id hash buffer and the nonce bigint
*/
static findGroupId(outpoint: string | Uint8Array, opReturnScript: Script | Uint8Array | null, authFlag: bigint, idFlag?: GroupIdFlag): GroupIdData;
private static _getGroupAddressBuffer;
/**
* Translates a group and additional data into a subgroup identifier
*
* @param group the group/token address or data buffer
* @param data the additional data
*
* @returns the subgroup id buffer
*/
static generateSubgroupId(group: Address | string | Uint8Array, data: number | string | Uint8Array): Uint8Array;
/**
* Extract the parent group from the provided subgroup.
*
* @remarks
* If the input is a group but not subgroup, the group itself return.
*
* @param subgroup the subgroup address or data buffer
* @returns the GroupId buffer
*/
static getParentGroupId(subgroup: Address | string | Uint8Array): Uint8Array;
/**
* Get group amount buffer from BigInt to include in output script
*
* @param amount
*/
static getAmountBuffer(amount: bigint): Uint8Array;
/**
* Get group amount value from Buffer
*
* @param amountBuf the amount buffer
* @param unsigned return value as unsigned bigint, default to false
*/
static getAmountValue(amountBuf: Uint8Array, unsigned?: boolean): bigint;
/**
* @param authFlag the utxo group quantity/authority
* @returns the nonce
*/
static getNonce(authFlag: bigint): bigint;
/**
* Check if the group id has the flag
*
* @param groupId the group id address or data buffer
* @param groupIdFlag the group id flag
* @returns true if this group id has the flag
*/
static hasIdFlag(groupId: Address | string | Uint8Array, groupIdFlag: GroupIdFlag): boolean;
/**
* Check if this authority and flag fit to this group creation
*
* @param groupId the group id address or data buffer
* @param authFlag the output group quantity/authority
* @param groupIdFlag optional. the group id flag
* @returns true if this is group creation data
*/
static isGroupCreation(groupId: Address | string | Uint8Array, authFlag: bigint, groupIdFlag?: GroupIdFlag): boolean;
/**
* Check if this group is is subgroup
*
* @param groupId the group id address or data buffer
* @returns true if this group id is subgroup
*/
static isSubgroup(groupId: Address | string | Uint8Array): boolean;
/**
* Check if the group quantity/authority is Authority flag
*
* @param authFlag the output group quantity/authority
* @returns true if this is authority flag
*/
static isAuthority(authFlag: bigint): boolean;
/**
* Check if the group quantity/authority allows minting
*
* @param authFlag the output group quantity/authority
* @returns true if this flag allows minting.
*/
static allowsMint(authFlag: bigint): boolean;
/**
* Check if the group quantity/authority allows melting
*
* @param authFlag the output group quantity/authority
* @returns true if this flag allows melting.
*/
static allowsMelt(authFlag: bigint): boolean;
/**
* Check if the group quantity/authority allows creation of new authorities
*
* @param authFlag the output group quantity/authority
* @returns true if this flag allows creation of authorities.
*/
static allowsRenew(authFlag: bigint): boolean;
/**
* Check if the group quantity/authority allows rescript
*
* @param authFlag the output group quantity/authority
* @returns true if this flag allows rescripting.
*/
static allowsRescript(authFlag: bigint): boolean;
/**
* Check if the group quantity/authority allows creation of subgroups
*
* @param authFlag the output group quantity/authority
* @returns true if this flag allows subgroups
*/
static allowsSubgroup(authFlag: bigint): boolean;
/**
* Verify token description document json signature
*
* @param jsonDoc the json TDD as string
* @param address nexa address that signed the doc
* @param signature the signature string. optional - if empty, extract from jsonDoc
*
* @returns true if signature match
*/
static verifyJsonDoc(jsonDoc: string, address: Address | string, signature?: string): boolean;
/**
* Sign token description document json
*
* @param jsonDoc the json TDD as string
* @param privKey private key to sign on the doc
*
* @returns the signature string
*/
static signJsonDoc(jsonDoc: string, privKey: PrivateKey): string;
}
export declare class Hash {
static sha1(buf: Uint8Array): Uint8Array;
static sha256(buf: Uint8Array): Uint8Array;
static sha512(buf: Uint8Array): Uint8Array;
static ripemd160(buf: Uint8Array): Uint8Array;
static sha256sha256(buf: Uint8Array): Uint8Array;
static sha256ripemd160(buf: Uint8Array): Uint8Array;
static sha256hmac(data: Uint8Array, key: Uint8Array): Uint8Array;
static sha512hmac(data: Uint8Array, key: Uint8Array): Uint8Array;
}
declare interface HDKeyBuffers {
version: Uint8Array;
depth: Uint8Array;
parentFingerPrint: Uint8Array;
childIndex: Uint8Array;
chainCode: Uint8Array;
checksum?: Uint8Array;
}
declare interface HDKeyDto {
network: string;
depth: number;
fingerPrint: number;
parentFingerPrint: number;
childIndex: number;
chainCode: string;
checksum: number;
}
export declare class HDPrivateKey implements IHDPrivateKey {
private static readonly MINIMUM_ENTROPY_BITS;
private static readonly BITS_TO_BYTES;
private static readonly MAXIMUM_ENTROPY_BITS;
private static readonly PrivateKeySize;
private static readonly PrivateKeyStart;
private static readonly PrivateKeyEnd;
private static readonly ChecksumStart;
private static readonly ChecksumEnd;
private _hdPublicKey?;
readonly privateKey: PrivateKey;
readonly publicKey: PublicKey;
readonly network: Network;
readonly depth: number;
readonly parentFingerPrint: Uint8Array;
readonly fingerPrint: Uint8Array;
readonly chainCode: Uint8Array;
readonly childIndex: number;
readonly checksum: Uint8Array;
readonly xprivkey: string;
/**
* Represents an instance of an hierarchically derived private key.
*
* More info on https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
*/
constructor(arg?: string | Uint8Array | IHDPrivateKey | HDPrivateKeyDto | HDPrivateKeyMinimalDto | Networkish);
private static _classifyArgument;
get hdPublicKey(): HDPublicKey;
get xpubkey(): string;
private static _isDtoObject;
private static _isMinimalDtoObject;
private static _isIHDPrivKey;
/**
* Verifies that a given path is valid.
*
* @param arg
* @param hardened
*/
static isValidPath(arg: string | number, hardened?: boolean): boolean;
static fromString(xprivkey: string): HDPrivateKey;
/**
* Returns the string representation of this private key (ext privkey).
*/
toString(): string;
/**
* Build a HDPrivateKey from a buffer
*
* @param buf
*/
static fromBuffer(buf: Uint8Array): HDPrivateKey;
/**
* Returns a buffer representation of the HDPrivateKey
*/
toBuffer(): Uint8Array;
toJSON: () => HDPrivateKeyDto;
/**
* Returns a plain object with a representation of this private key.
*/
toObject(): HDPrivateKeyDto;
static fromObject(arg: HDPrivateKeyDto): HDPrivateKey;
static fromMinimalObject(arg: HDPrivateKeyMinimalDto): HDPrivateKey;
/**
* Generate a private key from a seed, as described in BIP32
*
* @param seed
* @param network
* @return HDPrivateKey
*/
static fromSeed(seed: string | Uint8Array, network?: Networkish): HDPrivateKey;
/**
* Get a derived child based on a string or number.
*
* If the first argument is a string, it's parsed as the full path of
* derivation. Valid values for this argument include "m" (which returns the
* same private key), "m/0/1/40/2'/1000", where the ' quote means a hardened
* derivation.
*
* If the first argument is a number, the child with that index will be
* derived. If the second argument is truthy, the hardened version will be
* derived. See the example usage for clarification.
*
* @example
* ```javascript
* let parent = new HDPrivateKey('xprv...');
* let child_0_1_2h = parent.deriveChild(0).deriveChild(1).deriveChild(2, true);
* let copy_of_child_0_1_2h = parent.deriveChild("m/0/1/2'");
* assert(child_0_1_2h.xprivkey === copy_of_child_0_1_2h.xprivkey);
* ```
*
* @param arg
* @param hardened
* @return HDPrivateKey
*/
deriveChild(arg: string | number, hardened?: boolean): HDPrivateKey;
private _deriveWithNumber;
private _deriveFromString;
private static _buildFromSeed;
private static _buildFromObject;
private static _buildFromMinimalObject;
private static _buildFromSerialized;
/**
* Receives a object with buffers in all the properties and populates the
* internal structure
*/
private static _buildFromBuffers;
private static _validateBufferArguments;
private static _generateRandomly;
/**
* Will return the corresponding hd public key
*
* @returns An extended public key generated from the hd private key
*/
getHDPublicKey(): HDPublicKey;
/**
* Returns the console representation of this extended private key.
*/
inspect(): string;
}
export declare interface HDPrivateKeyBuffers extends HDKeyBuffers {
privateKey: Uint8Array;
}
export declare interface HDPrivateKeyDto extends HDKeyDto {
privateKey: string;
xprivkey: string;
}
export declare type HDPrivateKeyMinimalDto = Omit<HDPrivateKeyDto, 'xprivkey' | 'checksum' | 'fingerPrint'>;
export declare class HDPublicKey implements IHDPublicKey {
private static readonly PublicKeySize;
private static readonly PublicKeyStart;
private static readonly PublicKeyEnd;
private static readonly ChecksumStart;
private static readonly ChecksumEnd;
readonly publicKey: PublicKey;
readonly network: Network;
readonly depth: number;
readonly parentFingerPrint: Uint8Array;
readonly fingerPrint: Uint8Array;
readonly chainCode: Uint8Array;
readonly childIndex: number;
readonly checksum: Uint8Array;
readonly xpubkey: string;
/**
* The representation of an hierarchically derived public key.
*
* See https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
*
* @param arg
*/
constructor(arg: string | Uint8Array | HDPublicKeyDto | HDPublicKeyMinimalDto | IHDPublicKey | IHDPrivateKey);
private static _classifyArgument;
private static _isDtoObject;
private static _isMinimalDtoObject;
private static _isIHDPubKey;
private static _isIHDPrivKey;
/**
* Verifies that a given path is valid.
*
* @param arg
* @return {boolean}
*/
static isValidPath(arg: string | number): boolean;
/**
* Create a HDPublicKey from a buffer argument
*
* @param buf
*/
static fromBuffer(buf: Uint8Array): HDPublicKey;
/**
* Return a buffer representation of the xpubkey
*/
toBuffer(): Uint8Array;
static fromString(xpubkey: string): HDPublicKey;
/**
* Returns the base58 checked representation of the public key
* @return a string starting with "xpub..." in livenet
*/
toString(): string;
/**
* Returns the console representation of this extended public key.
*/
inspect(): string;
static fromObject(arg: HDPublicKeyDto): HDPublicKey;
static fromMinimalObject(arg: HDPublicKeyMinimalDto): HDPublicKey;
toJSON: () => HDPublicKeyDto;
/**
* Returns a plain JavaScript object with information to reconstruct a key.
*/
toObject(): HDPublicKeyDto;
/**
* Will return an address for the hdpubkey with its defined network
*
* @param type - optional parameter specifying the desired type of the address.
* default {@link AddressType.PayToScriptTemplate}
*
* @returns An address generated from the hd public key
*/
toAddress(type?: AddressType): Address;
/**
* Get a derivated child based on a string or number.
*
* If the first argument is a string, it's parsed as the full path of
* derivation. Valid values for this argument include "m" (which returns the
* same public key), "m/0/1/40/2/1000".
*
* Note that hardened keys can't be derived from a public extended key.
*
* If the first argument is a number, the child with that index will be
* derived. See the example usage for clarification.
*
* @example
* ```javascript
* let parent = new HDPublicKey('xpub...');
* let child_0_1_2 = parent.deriveChild(0).deriveChild(1).deriveChild(2);
* let copy_of_child_0_1_2 = parent.deriveChild("m/0/1/2");
* assert(child_0_1_2.xpubkey === copy_of_child_0_1_2.xpubkey);
* ```
*
* @param {string|number} arg
*/
deriveChild(arg: string | number, hardened?: boolean): HDPublicKey;
private _deriveWithNumber;
private _deriveFromString;
private static _buildFromObject;
private static _buildFromMinimalObject;
private static _buildFromHDPrivateKey;
private static _buildFromSerialized;
/**
* Receives a object with buffers in all the properties and populates the
* internal structure
*
* @param arg
*/
private static _buildFromBuffers;
private static _validateBufferArguments;
}
export declare interface HDPublicKeyBuffers extends HDKeyBuffers {
publicKey: Uint8Array;
}
export declare interface HDPublicKeyDto extends HDKeyDto {
publicKey: string;
xpubkey: string;
}
export declare type HDPublicKeyMinimalDto = Omit<HDPublicKeyDto, 'xpubkey' | 'checksum' | 'fingerPrint'>;
export declare interface IBlock {
header: IBlockHeader;
transactions: ITransaction[];
}
export declare interface IBlockHeader {
hash?: string;
prevHash: string | Uint8Array;
bits: number;
ancestorHash: string | Uint8Array;
merkleRoot: string | Uint8Array;
txFilter: string | Uint8Array;
time: number;
height: number;
chainWork: string | Uint8Array;
size: number;
txCount: number;
poolFee: number;
utxoCommitment: string | Uint8Array;
minerData: string | Uint8Array;
nonce: string | Uint8Array;
}
export declare interface IDigitalSignature {
hashbuf: Uint8Array;
endian?: "big" | "little";
privkey: IPrivateKey;
pubkey: IPublicKey;
sig?: ISignature;
verified?: boolean;
sign(): this;
verify(): this;
}
declare interface IHDKey {
network: Network;
depth: number;
parentFingerPrint: Uint8Array;
fingerPrint: Uint8Array;
chainCode: Uint8Array;
childIndex: number;
checksum: Uint8Array;
}
export declare interface IHDPrivateKey extends IHDKey {
privateKey: IPrivateKey;
publicKey?: IPublicKey;
xprivkey: string;
}
export declare interface IHDPublicKey extends IHDKey {
publicKey: IPublicKey;
xpubkey: string;
}
export declare interface IInput {
type?: number;
outpoint: string | Uint8Array;
scriptSig: string | Script;
amount: string | bigint;
sequenceNumber?: number;
output?: IOutput;
templateData?: ScriptTemplateObject;
}
export declare interface IMessage {
message: string;
}
export declare class Input implements IInput {
static readonly SEQUENCE_FINAL = 4294967295;
type: InputType;
outpoint: Uint8Array;
amount: bigint;
sequenceNumber: number;
output?: Output;
private _scriptSig;
constructor(params?: IInput);
get scriptSig(): Script;
set scriptSig(script: string | Script);
private _set;
static fromObject(obj: IInput): Input;
toJSON: () => IInput;
toObject(): IInput;
static fromBufferReader(br: BufferReader): Input;
toBufferWriter(writer?: BufferWriter, includeScript?: boolean): BufferWriter;
estimateSize(): number;
isFinal(): boolean;
clearSignatures(): this;
getSubscript(): Script;
/**
* @returns true if the provided private key can sign this input
*/
canSign(_privateKey: PrivateKey): boolean;
isFullySigned(): boolean;
addSignature(_signature: TxSignature): this;
}
export declare enum InputSighashType {
ALL = 0,
FIRSTN = 1,
THISIN = 2,
LAST_VALID = 2
}
export declare enum InputType {
UTXO = 0,
READ_ONLY = 1
}
export declare interface IOutput {
type?: number;
scriptPubKey: Script | string;
value: bigint | number | string;
address?: string;
groupId?: string;
groupAmount?: string;
}
export declare interface IPrivateKey {
compressed: boolean;
network: Network;
bn: BNExtended;
get publicKey(): IPublicKey;
toString(): string;
toWIF(): string;
toBigNumber(): BNExtended;
toBuffer(): Uint8Array;
toBufferNoPadding(): Uint8Array;
toPublicKey(): IPublicKey;
toJSON(): PrivateKeyDto;
toObject(): PrivateKeyDto;
inspect(): string;
}
export declare interface IPublicKey {
point: Point;
compressed?: boolean;
network?: Network;
toString(): string;
toJSON(): PublicKeyDto;
toObject(): PublicKeyDto;
toDER(): Uint8Array;
toBuffer(): Uint8Array;
inspect(): string;
}
export declare interface IScript {
chunks: ScriptChunk[];
}
export declare interface ISignature {
r: BNExtended;
s: BNExtended;
i?: number;
compressed?: boolean;
toBuffer(isSchnorr: boolean): Uint8Array;
}
export declare interface ITransaction {
id: string;
idem: string;
version: number;
inputs: IInput[];
outputs: IOutput[];
nLockTime: number;
fee?: number;
feePerByte?: number;
changeIndex?: number;
changeScript?: string;
}
export declare interface ITxSignature {
inputIndex: number;
publicKey: PublicKey | string;
subscript: Script | string;
signature: Signature | string;
sigType: SighashType | string;
}
export declare class Message implements IMessage {
static readonly MAGIC_BYTES: Uint8Array<ArrayBufferLike>;
message: string;
error?: string;
constructor(message: string);
/**
* Will sign a message with a given private key.
*
* @param privateKey An instance of PrivateKey
* @returns A base64 encoded compact signature
*/
sign(privateKey: PrivateKey): string;
/**
* Will return a boolean of the signature is valid for a given nexa address.
* If it isn't valid, the specific reason is accessible via the "error" member.
*
* @param nexaAddress A nexa address
* @param signatureString A base64 encoded compact signature
*/
verify(nexaAddress: Address | string, signatureString: string): boolean;
private _sign;
private _magicHash;
private _verify;
/**
* Instantiate a message from a message string
*
* @param str A string of the message
* @returns A new instance of a Message
*/
static fromString(str: string): Message;
/**
* Instantiate a message from JSON
*
* @param json An JSON string or Object with keys: message
* @returns A new instance of a Message
*/
static fromJSON(json: string | IMessage): Message;
/**
* @returns A plain object with the message information
*/
toObject(): IMessage;
/**
* @returns A JSON representation as string of the message information
*/
toJSON(): string;
/**
* Will return a the string representation of the message
*/
toString(): string;
/**
* Will return a string formatted for the console
*/
inspect(): string;
}
export declare class Network {
name: string;
alias: string;
prefix: string;
pubkeyhash: number;
privatekey: number;
scripthash: number;
xpubkey: number;
xprivkey: number;
networkMagic: Uint8Array;
port: number;
dnsSeeds: string[];
constructor(params: NetworkParams);
toString(): string;
}
/**
* Any type that can be used where a network is needed.
*/
export declare type Networkish = string | Network;
/**
* NetworkManager is a singleton service, containing map values that correspond to version
* numbers for each nexa network. Currently only supporting "mainnet"
* (a.k.a. "livenet") and "testnet", with option to add custom networks.
*
* @remarks should be used as singletone.
*
* @see {@linkcode NetworkManager.getInstance}
*/
export declare class NetworkManager {
private static readonly _instance;
private networks;
private _defaultNetwork;
get mainnet(): Network;
get testnet(): Network;
get defaultNetwork(): Network;
set defaultNetwork(network: Network);
/**
* @returns the singleton instance of NetworkManager
*/
static getInstance(): NetworkManager;
get(arg?: Networkish | number, key?: keyof Network): Network | undefined;
create(network: NetworkParams): Network;
add(network: Network | NetworkParams): void;
remove(network: Networkish | NetworkParams): void;
}
export declare interface NetworkParams {
name: string;
alias: string;
prefix: string;
pubkeyhash: number;
privatekey: number;
scripthash: number;
xpubkey: number;
xprivkey: number;
networkMagic: number;
port: number;
dnsSeeds: string[];
}
/**
* Singleton instance of {@link NetworkManager}
*/
export declare const Networks: NetworkManager;
/**
* Any type that can be used where a numeric value is needed.
*/
export declare type Numeric = number | bigint;
export declare enum Opcode {
OP_FALSE = 0,
OP_0 = 0,
OP_PUSHDATA1 = 76,
OP_PUSHDATA2 = 77,
OP_PUSHDATA4 = 78,
OP_1NEGATE = 79,
OP_RESERVED = 80,
OP_TRUE = 81,
OP_1 = 81,
OP_2 = 82,
OP_3 = 83,
OP_4 = 84,
OP_5 = 85,
OP_6 = 86,
OP_7 = 87,
OP_8 = 88,
OP_9 = 89,
OP_10 = 90,
OP_11 = 91,
OP_12 = 92,
OP_13 = 93,
OP_14 = 94,
OP_15 = 95,
OP_16 = 96,
OP_NOP = 97,
OP_INVALID_CONTROL1 = 98,
OP_IF = 99,
OP_NOTIF = 100,
OP_JUMP = 101,
OP_INVALID_CONTROL2 = 102,
OP_ELSE = 103,
OP_ENDIF = 104,
OP_VERIFY = 105,
OP_RETURN = 106,
OP_TOALTSTACK = 107,
OP_FROMALTSTACK = 108,
OP_2DROP = 109,
OP_2DUP = 110,
OP_3DUP = 111,
OP_2OVER = 112,
OP_2ROT = 113,
OP_2SWAP = 114,
OP_IFDUP = 115,
OP_DEPTH = 116,
OP_DROP = 117,
OP_DUP = 118,
OP_NIP = 119,
OP_OVER = 120,
OP_PICK = 121,
OP_ROLL = 122,
OP_ROT = 123,
OP_SWAP = 124,
OP_TUCK = 125,
OP_CAT = 126,
OP_SPLIT = 127,
OP_NUM2BIN = 128,
OP_BIN2NUM = 129,
OP_SIZE = 130,
OP_INVERT = 131,
OP_AND = 132,
OP_OR = 133,
OP_XOR = 134,
OP_EQUAL = 135,
OP_EQUALVERIFY = 136,
OP_RESERVED1 = 137,
OP_RESERVED2 = 138,
OP_1ADD = 139,
OP_1SUB = 140,
OP_2MUL = 141,
OP_2DIV = 142,
OP_NEGATE = 143,
OP_ABS = 144,
OP_NOT = 145,
OP_0NOTEQUAL = 146,
OP_ADD = 147,
OP_SUB = 148,
OP_MUL = 149,
OP_DIV = 150,
OP_MOD = 151,
OP_LSHIFT = 152,
OP_RSHIFT = 153,
OP_BOOLAND = 154,
OP_BOOLOR = 155,
OP_NUMEQUAL = 156,
OP_NUMEQUALVERIFY = 157,
OP_NUMNOTEQUAL = 158,
OP_LESSTHAN = 159,
OP_GREATERTHAN = 160,
OP_LESSTHANOREQUAL = 161,
OP_GREATERTHANOREQUAL = 162,
OP_MIN = 163,
OP_MAX = 164,
OP_WITHIN = 165,
OP_RIPEMD160 = 166,
OP_SHA1 = 167,
OP_SHA256 = 168,
OP_HASH160 = 169,
OP_HASH256 = 170,
OP_CODESEPARATOR = 171,
OP_CHECKSIG = 172,
OP_CHECKSIGVERIFY = 173,
OP_CHECKMULTISIG = 174,
OP_CHECKMULTISIGVERIFY = 175,
OP_NOP2 = 177,
OP_CHECKLOCKTIMEVERIFY = 177,
OP_NOP3 = 178,
OP_CHECKSEQUENCEVERIFY = 178,
OP_NOP1 = 176,
OP_NOP4 = 179,
OP_NOP5 = 180,
OP_NOP6 = 181,
OP_NOP7 = 182,
OP_NOP8 = 183,
OP_NOP9 = 184,
OP_NOP10 = 185,
OP_CHECKDATASIG = 186,
OP_CHECKDATASIGVERIFY = 187,
OP_REVERSEBYTES = 188,
OP_INP