UNPKG

@bnb-chain/greenfield-js-sdk

Version:
1,293 lines (1,276 loc) 377 kB
import 'reflect-metadata'; import { injectable, inject, container, delay as delay$1 } from 'tsyringe'; import { Any } from '@bnb-chain/greenfield-cosmos-types/google/protobuf/any'; import * as base64 from '@ethersproject/base64'; import { hexlify, arrayify, joinSignature } from '@ethersproject/bytes'; import { toUtf8String, toUtf8Bytes } from '@ethersproject/strings'; import cloneDeep from 'lodash.clonedeep'; import get from 'lodash.get'; import mapValues from 'lodash.mapvalues'; import set from 'lodash.set'; import sortBy from 'lodash.sortby'; import { TypedDataUtils, SignTypedDataVersion, signTypedData } from '@metamask/eth-sig-util'; import { ServiceClientImpl as ServiceClientImpl$1 } from '@bnb-chain/greenfield-cosmos-types/cosmos/base/tendermint/v1beta1/query'; import Long from 'long'; export { default as Long } from 'long'; import { QueryClientImpl } from '@bnb-chain/greenfield-cosmos-types/cosmos/auth/v1beta1/query'; import { QueryClientImpl as QueryClientImpl$1 } from '@bnb-chain/greenfield-cosmos-types/cosmos/bank/v1beta1/query'; import { QueryClientImpl as QueryClientImpl$5 } from '@bnb-chain/greenfield-cosmos-types/cosmos/crosschain/v1/query'; import { MsgClientImpl, MsgSetWithdrawAddress, MsgWithdrawValidatorCommission, MsgWithdrawDelegatorReward, MsgFundCommunityPool } from '@bnb-chain/greenfield-cosmos-types/cosmos/distribution/v1beta1/tx'; import { QueryClientImpl as QueryClientImpl$8 } from '@bnb-chain/greenfield-cosmos-types/cosmos/feegrant/v1beta1/query'; import { QueryClientImpl as QueryClientImpl$a } from '@bnb-chain/greenfield-cosmos-types/cosmos/gashub/v1beta1/query'; import { QueryClientImpl as QueryClientImpl$6 } from '@bnb-chain/greenfield-cosmos-types/cosmos/oracle/v1/query'; import { QueryClientImpl as QueryClientImpl$c } from '@bnb-chain/greenfield-cosmos-types/cosmos/staking/v1beta1/query'; import { QueryClientImpl as QueryClientImpl$7 } from '@bnb-chain/greenfield-cosmos-types/greenfield/bridge/query'; import { QueryClientImpl as QueryClientImpl$4 } from '@bnb-chain/greenfield-cosmos-types/greenfield/challenge/query'; import { QueryClientImpl as QueryClientImpl$2 } from '@bnb-chain/greenfield-cosmos-types/greenfield/payment/query'; import { QueryClientImpl as QueryClientImpl$3 } from '@bnb-chain/greenfield-cosmos-types/greenfield/sp/query'; import { QueryClientImpl as QueryClientImpl$9 } from '@bnb-chain/greenfield-cosmos-types/greenfield/storage/query'; import { QueryClientImpl as QueryClientImpl$b } from '@bnb-chain/greenfield-cosmos-types/greenfield/virtualgroup/query'; import { QueryClient, setupAuthExtension, setupAuthzExtension, setupBankExtension, setupDistributionExtension, setupFeegrantExtension, setupGovExtension, setupIbcExtension, setupMintExtension, setupSlashingExtension, setupStakingExtension, setupTxExtension, createProtobufRpcClient, StargateClient } from '@cosmjs/stargate'; import { Tendermint37Client } from '@cosmjs/tendermint-rpc'; import { UInt64Value } from '@bnb-chain/greenfield-cosmos-types/greenfield/common/wrapper'; import { actionTypeFromJSON, principalTypeFromJSON } from '@bnb-chain/greenfield-cosmos-types/greenfield/permission/common'; import * as common from '@bnb-chain/greenfield-cosmos-types/greenfield/permission/common'; export { common as PermissionTypes }; import { visibilityTypeFromJSON, ObjectStatus } from '@bnb-chain/greenfield-cosmos-types/greenfield/storage/common'; import * as common$1 from '@bnb-chain/greenfield-cosmos-types/greenfield/storage/common'; export { common$1 as StorageEnums }; export { BucketStatus, ObjectStatus, RedundancyType, SourceType, VisibilityType } from '@bnb-chain/greenfield-cosmos-types/greenfield/storage/common'; import { MsgPutPolicy, MsgDeletePolicy, MsgSetTag, MsgSetBucketFlowRateLimit, MsgCreateBucket, MsgDeleteBucket, MsgToggleSPAsDelegatedAgent, MsgUpdateBucketInfo, MsgCancelMigrateBucket, MsgMigrateBucket, MsgMirrorGroup, MsgMirrorBucket, MsgMirrorObject, MsgCreateGroup, MsgDeleteGroup, MsgUpdateGroupMember, MsgUpdateGroupExtra, MsgLeaveGroup, MsgCreateObject, MsgCancelCreateObject, MsgDeleteObject, MsgUpdateObjectInfo } from '@bnb-chain/greenfield-cosmos-types/greenfield/storage/tx'; import { PickVGFStrategy } from '@bnb-chain/greenfield-cosmos-types/greenfield/virtualgroup/common'; import { fromTimestamp, bytesFromBase64, base64FromBytes } from '@bnb-chain/greenfield-cosmos-types/helpers'; export * from '@bnb-chain/greenfield-cosmos-types/helpers'; import fetch, { Headers as Headers$1 } from 'cross-fetch'; import { MsgSubmit, MsgAttest } from '@bnb-chain/greenfield-cosmos-types/greenfield/challenge/tx'; import { MsgClaim } from '@bnb-chain/greenfield-cosmos-types/cosmos/oracle/v1/tx'; import { MsgTransferOut } from '@bnb-chain/greenfield-cosmos-types/greenfield/bridge/tx'; import { MsgGrantAllowance, MsgRevokeAllowance } from '@bnb-chain/greenfield-cosmos-types/cosmos/feegrant/v1beta1/tx'; import { recoverPublicKey, computePublicKey, SigningKey } from '@ethersproject/signing-key'; import { MsgCreatePaymentAccount, MsgDeposit, MsgWithdraw, MsgDisableRefund } from '@bnb-chain/greenfield-cosmos-types/greenfield/payment/tx'; import { voteOptionToJSON } from '@bnb-chain/greenfield-cosmos-types/cosmos/gov/v1/gov'; import { MsgVote, MsgSubmitProposal } from '@bnb-chain/greenfield-cosmos-types/cosmos/gov/v1/tx'; import { XMLParser } from 'fast-xml-parser'; import superagent from 'superagent'; import { BasicAllowance, AllowedMsgAllowance } from '@bnb-chain/greenfield-cosmos-types/cosmos/feegrant/v1beta1/feegrant'; import { MsgCreateValidator, MsgEditValidator } from '@bnb-chain/greenfield-cosmos-types/cosmos/staking/v1beta1/tx'; import { MsgSettle } from '@bnb-chain/greenfield-cosmos-types/greenfield/virtualgroup/tx'; import { PubKey } from '@bnb-chain/greenfield-cosmos-types/cosmos/crypto/secp256k1/keys'; import * as timestamp from '@bnb-chain/greenfield-cosmos-types/google/protobuf/timestamp'; export { timestamp as TimestampTypes }; import { ResourceType } from '@bnb-chain/greenfield-cosmos-types/greenfield/resource/types'; import dayjs from 'dayjs'; import utc from 'dayjs/plugin/utc'; import timezone from 'dayjs/plugin/timezone'; import { formatEther } from '@ethersproject/units'; import { isNode } from 'browser-or-node'; import { Status } from '@bnb-chain/greenfield-cosmos-types/greenfield/sp/types'; import { ServiceClientImpl, SimulateRequest } from '@bnb-chain/greenfield-cosmos-types/cosmos/tx/v1beta1/service'; import { TxRaw, TxBody, Tx, AuthInfo } from '@bnb-chain/greenfield-cosmos-types/cosmos/tx/v1beta1/tx'; import { makeAuthInfoBytes } from '@cosmjs/proto-signing'; import { BaseAccount } from '@bnb-chain/greenfield-cosmos-types/cosmos/auth/v1beta1/auth'; import { MsgMultiSend, MsgSend } from '@bnb-chain/greenfield-cosmos-types/cosmos/bank/v1beta1/tx'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; const typeWrapper = (type, msg) => { return { ...msg, type, }; }; const generateMsg = (typeUrl, msgBytes) => { return Any.fromPartial({ typeUrl, value: msgBytes, }); }; const createEIP712 = (types, chainId, message) => { return { types, primaryType: 'Tx', domain: { name: 'Greenfield Tx', version: '1.0.0', chainId, verifyingContract: '0x71e835aff094655dEF897fbc85534186DbeaB75d', salt: '0', }, message, }; }; const generateMessage = (accountNumber, sequence, chainCosmosId, memo, fee, msg, timeoutHeight) => { let res = { account_number: accountNumber, chain_id: chainCosmosId, sequence, memo, fee, timeout_height: timeoutHeight, }; if (Object.keys(msg).length == 0) { return res; } if (msg.hasOwnProperty('msg1')) { res = { ...res, ...msg, }; } else { res.msg1 = msg; } return res; }; const generateTypes = (newTypes) => { const types = { Coin: [ { name: 'denom', type: 'string' }, { name: 'amount', type: 'uint256' }, ], EIP712Domain: [ { name: 'name', type: 'string' }, { name: 'version', type: 'string' }, { name: 'chainId', type: 'uint256' }, { name: 'verifyingContract', type: 'string' }, { name: 'salt', type: 'string' }, ], Fee: [ { name: 'amount', type: 'Coin[]' }, { name: 'gas_limit', type: 'uint256' }, { name: 'payer', type: 'string' }, { name: 'granter', type: 'string' }, ], Tx: [ { name: 'account_number', type: 'uint256', }, { name: 'chain_id', type: 'uint256', }, { name: 'fee', type: 'Fee', }, { name: 'memo', type: 'string', }, { name: 'sequence', type: 'uint256', }, { name: 'timeout_height', type: 'uint256', }, ], }; if (Array.isArray(newTypes)) { for (let i = 0; i < newTypes.length; i++) { types.Tx.push({ name: `msg${i + 1}`, type: `Msg${i + 1}`, }); } Object.assign(types, ...newTypes); } else if (typeof newTypes === 'object') { const msgLen = Object.keys(newTypes).filter((k) => k.startsWith('Msg')).length; for (let i = 0; i < msgLen; i++) { types.Tx.push({ name: `msg${i + 1}`, type: `Msg${i + 1}`, }); } Object.assign(types, newTypes); } else { types.Tx.push({ name: 'msg1', type: 'Msg1', }); Object.assign(types, newTypes); } return mapValues(types, (o) => { return sortBy(o, ['name']); }); }; const generateFee = (amount, denom, gas_limit, payer, granter) => { return { amount: [ { amount, denom, }, ], gas_limit, payer, granter, }; }; const mergeMultiEip712 = (eip712s) => { const res = []; eip712s.forEach((eip712, index) => { if (index === 0) { res.push(eip712); } else { const str = JSON.stringify(eip712); const reStr = str.replaceAll('Msg1', `Msg${index + 1}`); res.push(JSON.parse(reStr)); } }); return res; }; const mergeMultiMessage = (txs) => { const msgs = txs.map((tx) => tx.MsgSDK); const res = {}; msgs.forEach((msg, index) => { res[`msg${index + 1}`] = { ...msg, type: txs[index].typeUrl, }; }); return res; }; const findAnyType = (msgData) => { const results = []; function findTypeAnyFields(obj, path = []) { if (typeof obj === 'object' && obj !== null) { for (const key in obj) { const newPath = [...path, key]; // console.log(newPath.join('.')); if (key === 'value') { results.push(newPath); } findTypeAnyFields(obj[key], newPath); } } } findTypeAnyFields(msgData); return results; }; const convertAnyTypeData = (msgData, fields) => { const resData = cloneDeep(msgData); fields.forEach((field) => { const path = field.join('.'); const anyValue = get(resData, path); // console.log('path', path, anyValue); if (anyValue.startsWith('ZXl')) { // TypeAny: need base64 decode set(resData, path, toUtf8String(base64.decode(anyValue))); } else if (anyValue.startsWith('eyJ')) { // TypeAny[]: need base64 decode and encode hex set(resData, path, hexlify(base64.decode(anyValue))); } else ; }); return resData; }; function number(n) { if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`); } function bool(b) { if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`); } // copied from utils function isBytes$3(a) { return (a instanceof Uint8Array || (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); } function bytes(b, ...lengths) { if (!isBytes$3(b)) throw new Error('Uint8Array expected'); if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); } function hash(h) { if (typeof h !== 'function' || typeof h.create !== 'function') throw new Error('Hash should be wrapped by utils.wrapConstructor'); number(h.outputLen); number(h.blockLen); } function exists(instance, checkFinished = true) { if (instance.destroyed) throw new Error('Hash instance has been destroyed'); if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); } function output$1(out, instance) { bytes(out); const min = instance.outputLen; if (out.length < min) { throw new Error(`digestInto() expects output buffer of length at least ${min}`); } } const assert = { number, bool, bytes, hash, exists, output: output$1 }; const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); // Cast array to view const createView$1 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); // The rotate right (circular right shift) operation for uint32 const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; // The byte swap operation for uint32 const byteSwap = (word) => ((word << 24) & 0xff000000) | ((word << 8) & 0xff0000) | ((word >>> 8) & 0xff00) | ((word >>> 24) & 0xff); // In place byte swap for Uint32Array function byteSwap32(arr) { for (let i = 0; i < arr.length; i++) { arr[i] = byteSwap(arr[i]); } } // Array where index 0xf0 (240) is mapped to string 'f0' const hexes$2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); /** * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' */ function bytesToHex$2(bytes$1) { bytes(bytes$1); // pre-caching improves the speed 6x let hex = ''; for (let i = 0; i < bytes$1.length; i++) { hex += hexes$2[bytes$1[i]]; } return hex; } /** * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) */ function utf8ToBytes$2(str) { if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 } /** * Normalizes (non-hex) string or Uint8Array to Uint8Array. * Warning: when Uint8Array is passed, it would NOT get copied. * Keep in mind for future mutable operations. */ function toBytes$1(data) { if (typeof data === 'string') data = utf8ToBytes$2(data); bytes(data); return data; } /** * Copies several Uint8Arrays into one. */ function concatBytes$2(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; bytes(a); sum += a.length; } const res = new Uint8Array(sum); for (let i = 0, pad = 0; i < arrays.length; i++) { const a = arrays[i]; res.set(a, pad); pad += a.length; } return res; } // For runtime check if class implements interface class Hash$1 { // Safe version that clones internal state clone() { return this._cloneInto(); } } function wrapConstructor$1(hashCons) { const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest(); const tmp = hashCons(); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = () => hashCons(); return hashC; } /** * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. */ function randomBytes$1(bytesLength = 32) { if (crypto$1 && typeof crypto$1.getRandomValues === 'function') { return crypto$1.getRandomValues(new Uint8Array(bytesLength)); } throw new Error('crypto.getRandomValues must be defined'); } // Polyfill for Safari 14 function setBigUint64$1(view, byteOffset, value, isLE) { if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); const _32n = BigInt(32); const _u32_max = BigInt(0xffffffff); const wh = Number((value >> _32n) & _u32_max); const wl = Number(value & _u32_max); const h = isLE ? 4 : 0; const l = isLE ? 0 : 4; view.setUint32(byteOffset + h, wh, isLE); view.setUint32(byteOffset + l, wl, isLE); } // Choice: a ? b : c const Chi = (a, b, c) => (a & b) ^ (~a & c); // Majority function, true if any two inpust is true const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); /** * Merkle-Damgard hash construction base class. * Could be used to create MD5, RIPEMD, SHA1, SHA2. */ class HashMD$1 extends Hash$1 { constructor(blockLen, outputLen, padOffset, isLE) { super(); this.blockLen = blockLen; this.outputLen = outputLen; this.padOffset = padOffset; this.isLE = isLE; this.finished = false; this.length = 0; this.pos = 0; this.destroyed = false; this.buffer = new Uint8Array(blockLen); this.view = createView$1(this.buffer); } update(data) { exists(this); const { view, buffer, blockLen } = this; data = toBytes$1(data); const len = data.length; for (let pos = 0; pos < len;) { const take = Math.min(blockLen - this.pos, len - pos); // Fast path: we have at least one block in input, cast it to view and process if (take === blockLen) { const dataView = createView$1(data); for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); continue; } buffer.set(data.subarray(pos, pos + take), this.pos); this.pos += take; pos += take; if (this.pos === blockLen) { this.process(view, 0); this.pos = 0; } } this.length += data.length; this.roundClean(); return this; } digestInto(out) { exists(this); output$1(out, this); this.finished = true; // Padding // We can avoid allocation of buffer for padding completely if it // was previously not allocated here. But it won't change performance. const { buffer, view, blockLen, isLE } = this; let { pos } = this; // append the bit '1' to the message buffer[pos++] = 0b10000000; this.buffer.subarray(pos).fill(0); // we have less than padOffset left in buffer, so we cannot put length in // current block, need process it and pad again if (this.padOffset > blockLen - pos) { this.process(view, 0); pos = 0; } // Pad until full block byte with zeros for (let i = pos; i < blockLen; i++) buffer[i] = 0; // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. // So we just write lowest 64 bits of that value. setBigUint64$1(view, blockLen - 8, BigInt(this.length * 8), isLE); this.process(view, 0); const oview = createView$1(out); const len = this.outputLen; // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit'); const outLen = len / 4; const state = this.get(); if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE); } digest() { const { buffer, outputLen } = this; this.digestInto(buffer); const res = buffer.slice(0, outputLen); this.destroy(); return res; } _cloneInto(to) { to || (to = new this.constructor()); to.set(...this.get()); const { blockLen, buffer, length, finished, destroyed, pos } = this; to.length = length; to.pos = pos; to.finished = finished; to.destroyed = destroyed; if (length % blockLen) to.buffer.set(buffer); return to; } } // SHA2-256 need to try 2^128 hashes to execute birthday attack. // BTC network is doing 2^67 hashes/sec as per early 2023. // Round constants: // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) // prettier-ignore const SHA256_K = /* @__PURE__ */ new Uint32Array([ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]); // Initial state: // first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 // prettier-ignore const SHA256_IV = /* @__PURE__ */ new Uint32Array([ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]); // Temporary buffer, not used to store anything between runs // Named this way because it matches specification. const SHA256_W = /* @__PURE__ */ new Uint32Array(64); class SHA256 extends HashMD$1 { constructor() { super(64, 32, 8, false); // We cannot use array here since array allows indexing by variable // which means optimizer/compiler cannot use registers. this.A = SHA256_IV[0] | 0; this.B = SHA256_IV[1] | 0; this.C = SHA256_IV[2] | 0; this.D = SHA256_IV[3] | 0; this.E = SHA256_IV[4] | 0; this.F = SHA256_IV[5] | 0; this.G = SHA256_IV[6] | 0; this.H = SHA256_IV[7] | 0; } get() { const { A, B, C, D, E, F, G, H } = this; return [A, B, C, D, E, F, G, H]; } // prettier-ignore set(A, B, C, D, E, F, G, H) { this.A = A | 0; this.B = B | 0; this.C = C | 0; this.D = D | 0; this.E = E | 0; this.F = F | 0; this.G = G | 0; this.H = H | 0; } process(view, offset) { // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false); for (let i = 16; i < 64; i++) { const W15 = SHA256_W[i - 15]; const W2 = SHA256_W[i - 2]; const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; } // Compression function main loop, 64 rounds let { A, B, C, D, E, F, G, H } = this; for (let i = 0; i < 64; i++) { const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); const T2 = (sigma0 + Maj(A, B, C)) | 0; H = G; G = F; F = E; E = (D + T1) | 0; D = C; C = B; B = A; A = (T1 + T2) | 0; } // Add the compressed chunk to the current hash value A = (A + this.A) | 0; B = (B + this.B) | 0; C = (C + this.C) | 0; D = (D + this.D) | 0; E = (E + this.E) | 0; F = (F + this.F) | 0; G = (G + this.G) | 0; H = (H + this.H) | 0; this.set(A, B, C, D, E, F, G, H); } roundClean() { SHA256_W.fill(0); } destroy() { this.set(0, 0, 0, 0, 0, 0, 0, 0); this.buffer.fill(0); } } /** * SHA2-256 hash function * @param message - data that would be hashed */ const sha256 = /* @__PURE__ */ wrapConstructor$1(() => new SHA256()); /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ // 100 lines of code in the file are duplicated from noble-hashes (utils). // This is OK: `abstract` directory does not use noble-hashes. // User may opt-in into using different hashing library. This way, noble-hashes // won't be included into their bundle. const _0n$8 = /* @__PURE__ */ BigInt(0); const _1n$a = /* @__PURE__ */ BigInt(1); const _2n$7 = /* @__PURE__ */ BigInt(2); function isBytes$2(a) { return (a instanceof Uint8Array || (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); } function abytes$2(item) { if (!isBytes$2(item)) throw new Error('Uint8Array expected'); } // Array where index 0xf0 (240) is mapped to string 'f0' const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); /** * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' */ function bytesToHex$1(bytes) { abytes$2(bytes); // pre-caching improves the speed 6x let hex = ''; for (let i = 0; i < bytes.length; i++) { hex += hexes$1[bytes[i]]; } return hex; } function numberToHexUnpadded(num) { const hex = num.toString(16); return hex.length & 1 ? `0${hex}` : hex; } function hexToNumber$1(hex) { if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); // Big Endian return BigInt(hex === '' ? '0' : `0x${hex}`); } // We use optimized technique to convert hex string to byte array const asciis$1 = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; function asciiToBase16$1(char) { if (char >= asciis$1._0 && char <= asciis$1._9) return char - asciis$1._0; if (char >= asciis$1._A && char <= asciis$1._F) return char - (asciis$1._A - 10); if (char >= asciis$1._a && char <= asciis$1._f) return char - (asciis$1._a - 10); return; } /** * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) */ function hexToBytes$2(hex) { if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); const hl = hex.length; const al = hl / 2; if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl); const array = new Uint8Array(al); for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { const n1 = asciiToBase16$1(hex.charCodeAt(hi)); const n2 = asciiToBase16$1(hex.charCodeAt(hi + 1)); if (n1 === undefined || n2 === undefined) { const char = hex[hi] + hex[hi + 1]; throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); } array[ai] = n1 * 16 + n2; } return array; } // BE: Big Endian, LE: Little Endian function bytesToNumberBE$1(bytes) { return hexToNumber$1(bytesToHex$1(bytes)); } function bytesToNumberLE$1(bytes) { abytes$2(bytes); return hexToNumber$1(bytesToHex$1(Uint8Array.from(bytes).reverse())); } function numberToBytesBE$1(n, len) { return hexToBytes$2(n.toString(16).padStart(len * 2, '0')); } function numberToBytesLE$1(n, len) { return numberToBytesBE$1(n, len).reverse(); } // Unpadded, rarely used function numberToVarBytesBE(n) { return hexToBytes$2(numberToHexUnpadded(n)); } /** * Takes hex string or Uint8Array, converts to Uint8Array. * Validates output length. * Will throw error for other types. * @param title descriptive title for an error e.g. 'private key' * @param hex hex string or Uint8Array * @param expectedLength optional, will compare to result array's length * @returns */ function ensureBytes$1(title, hex, expectedLength) { let res; if (typeof hex === 'string') { try { res = hexToBytes$2(hex); } catch (e) { throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); } } else if (isBytes$2(hex)) { // Uint8Array.from() instead of hash.slice() because node.js Buffer // is instance of Uint8Array, and its slice() creates **mutable** copy res = Uint8Array.from(hex); } else { throw new Error(`${title} must be hex string or Uint8Array`); } const len = res.length; if (typeof expectedLength === 'number' && len !== expectedLength) throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); return res; } /** * Copies several Uint8Arrays into one. */ function concatBytes$1(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; abytes$2(a); sum += a.length; } const res = new Uint8Array(sum); for (let i = 0, pad = 0; i < arrays.length; i++) { const a = arrays[i]; res.set(a, pad); pad += a.length; } return res; } // Compares 2 u8a-s in kinda constant time function equalBytes(a, b) { if (a.length !== b.length) return false; let diff = 0; for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i]; return diff === 0; } /** * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) */ function utf8ToBytes$1(str) { if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 } // Bit operations /** * Calculates amount of bits in a bigint. * Same as `n.toString(2).length` */ function bitLen$1(n) { let len; for (len = 0; n > _0n$8; n >>= _1n$a, len += 1) ; return len; } /** * Gets single bit at position. * NOTE: first bit position is 0 (same as arrays) * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` */ function bitGet(n, pos) { return (n >> BigInt(pos)) & _1n$a; } /** * Sets single bit at position. */ function bitSet(n, pos, value) { return n | ((value ? _1n$a : _0n$8) << BigInt(pos)); } /** * Calculate mask for N bits. Not using ** operator with bigints because of old engines. * Same as BigInt(`0b${Array(i).fill('1').join('')}`) */ const bitMask$1 = (n) => (_2n$7 << BigInt(n - 1)) - _1n$a; // DRBG const u8n = (data) => new Uint8Array(data); // creates Uint8Array const u8fr = (arr) => Uint8Array.from(arr); // another shortcut /** * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. * @returns function that will call DRBG until 2nd arg returns something meaningful * @example * const drbg = createHmacDRBG<Key>(32, 32, hmac); * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined */ function createHmacDrbg(hashLen, qByteLen, hmacFn) { if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number'); if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number'); if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function'); // Step B, Step C: set hashLen to 8*ceil(hlen/8) let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same let i = 0; // Iterations counter, will throw when over 1000 const reset = () => { v.fill(1); k.fill(0); i = 0; }; const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) const reseed = (seed = u8n()) => { // HMAC-DRBG reseed() function. Steps D-G k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) v = h(); // v = hmac(k || v) if (seed.length === 0) return; k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) v = h(); // v = hmac(k || v) }; const gen = () => { // HMAC-DRBG generate() function if (i++ >= 1000) throw new Error('drbg: tried 1000 values'); let len = 0; const out = []; while (len < qByteLen) { v = h(); const sl = v.slice(); out.push(sl); len += v.length; } return concatBytes$1(...out); }; const genUntil = (seed, pred) => { reset(); reseed(seed); // Steps D-G let res = undefined; // Step H: grind until k is in [1..n-1] while (!(res = pred(gen()))) reseed(); reset(); return res; }; return genUntil; } // Validating curves and fields const validatorFns$1 = { bigint: (val) => typeof val === 'bigint', function: (val) => typeof val === 'function', boolean: (val) => typeof val === 'boolean', string: (val) => typeof val === 'string', stringOrUint8Array: (val) => typeof val === 'string' || isBytes$2(val), isSafeInteger: (val) => Number.isSafeInteger(val), array: (val) => Array.isArray(val), field: (val, object) => object.Fp.isValid(val), hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), }; // type Record<K extends string | number | symbol, T> = { [P in K]: T; } function validateObject$1(object, validators, optValidators = {}) { const checkField = (fieldName, type, isOptional) => { const checkVal = validatorFns$1[type]; if (typeof checkVal !== 'function') throw new Error(`Invalid validator "${type}", expected function`); const val = object[fieldName]; if (isOptional && val === undefined) return; if (!checkVal(val, object)) { throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); } }; for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type, false); for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type, true); return object; } // validate type tests // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! // // Should fail type-check // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); // const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); // const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); var ut = /*#__PURE__*/Object.freeze({ __proto__: null, isBytes: isBytes$2, abytes: abytes$2, bytesToHex: bytesToHex$1, numberToHexUnpadded: numberToHexUnpadded, hexToNumber: hexToNumber$1, hexToBytes: hexToBytes$2, bytesToNumberBE: bytesToNumberBE$1, bytesToNumberLE: bytesToNumberLE$1, numberToBytesBE: numberToBytesBE$1, numberToBytesLE: numberToBytesLE$1, numberToVarBytesBE: numberToVarBytesBE, ensureBytes: ensureBytes$1, concatBytes: concatBytes$1, equalBytes: equalBytes, utf8ToBytes: utf8ToBytes$1, bitLen: bitLen$1, bitGet: bitGet, bitSet: bitSet, bitMask: bitMask$1, createHmacDrbg: createHmacDrbg, validateObject: validateObject$1 }); /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ // prettier-ignore const _0n$7 = BigInt(0), _1n$9 = BigInt(1), _2n$6 = BigInt(2), _3n$2 = BigInt(3); // prettier-ignore const _4n$1 = BigInt(4), _5n$2 = BigInt(5), _8n$3 = BigInt(8); // prettier-ignore BigInt(9); BigInt(16); // Calculates a modulo b function mod$1(a, b) { const result = a % b; return result >= _0n$7 ? result : b + result; } /** * Efficiently raise num to power and do modular division. * Unsafe in some contexts: uses ladder, so can expose bigint bits. * @example * pow(2n, 6n, 11n) // 64n % 11n == 9n */ // TODO: use field version && remove function pow$1(num, power, modulo) { if (modulo <= _0n$7 || power < _0n$7) throw new Error('Expected power/modulo > 0'); if (modulo === _1n$9) return _0n$7; let res = _1n$9; while (power > _0n$7) { if (power & _1n$9) res = (res * num) % modulo; num = (num * num) % modulo; power >>= _1n$9; } return res; } // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) function pow2$1(x, power, modulo) { let res = x; while (power-- > _0n$7) { res *= res; res %= modulo; } return res; } // Inverses number over modulo function invert$1(number, modulo) { if (number === _0n$7 || modulo <= _0n$7) { throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); } // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. let a = mod$1(number, modulo); let b = modulo; // prettier-ignore let x = _0n$7, u = _1n$9; while (a !== _0n$7) { // JIT applies optimization if those two lines follow each other const q = b / a; const r = b % a; const m = x - u * q; // prettier-ignore b = a, a = r, x = u, u = m; } const gcd = b; if (gcd !== _1n$9) throw new Error('invert: does not exist'); return mod$1(x, modulo); } /** * Tonelli-Shanks square root search algorithm. * 1. https://eprint.iacr.org/2012/685.pdf (page 12) * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks * Will start an infinite loop if field order P is not prime. * @param P field order * @returns function that takes field Fp (created from P) and number n */ function tonelliShanks$1(P) { // Legendre constant: used to calculate Legendre symbol (a | p), // which denotes the value of a^((p-1)/2) (mod p). // (a | p) ≡ 1 if a is a square (mod p) // (a | p) ≡ -1 if a is not a square (mod p) // (a | p) ≡ 0 if a ≡ 0 (mod p) const legendreC = (P - _1n$9) / _2n$6; let Q, S, Z; // Step 1: By factoring out powers of 2 from p - 1, // find q and s such that p - 1 = q*(2^s) with q odd for (Q = P - _1n$9, S = 0; Q % _2n$6 === _0n$7; Q /= _2n$6, S++) ; // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq for (Z = _2n$6; Z < P && pow$1(Z, legendreC, P) !== P - _1n$9; Z++) ; // Fast-path if (S === 1) { const p1div4 = (P + _1n$9) / _4n$1; return function tonelliFast(Fp, n) { const root = Fp.pow(n, p1div4); if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); return root; }; } // Slow-path const Q1div2 = (Q + _1n$9) / _2n$6; return function tonelliSlow(Fp, n) { // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root'); let r = S; // TODO: will fail at Fp2/etc let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b let x = Fp.pow(n, Q1div2); // first guess at the square root let b = Fp.pow(n, Q); // first guess at the fudge factor while (!Fp.eql(b, Fp.ONE)) { if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) // Find m such b^(2^m)==1 let m = 1; for (let t2 = Fp.sqr(b); m < r; m++) { if (Fp.eql(t2, Fp.ONE)) break; t2 = Fp.sqr(t2); // t2 *= t2 } // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow const ge = Fp.pow(g, _1n$9 << BigInt(r - m - 1)); // ge = 2^(r-m-1) g = Fp.sqr(ge); // g = ge * ge x = Fp.mul(x, ge); // x *= ge b = Fp.mul(b, g); // b *= g r = m; } return x; }; } function FpSqrt$1(P) { // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). // P ≡ 3 (mod 4) // √n = n^((P+1)/4) if (P % _4n$1 === _3n$2) { // Not all roots possible! // const ORDER = // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; // const NUM = 72057594037927816n; const p1div4 = (P + _1n$9) / _4n$1; return function sqrt3mod4(Fp, n) { const root = Fp.pow(n, p1div4); // Throw if root**2 != n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); return root; }; } // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) if (P % _8n$3 === _5n$2) { const c1 = (P - _5n$2) / _8n$3; return function sqrt5mod8(Fp, n) { const n2 = Fp.mul(n, _2n$6); const v = Fp.pow(n2, c1); const nv = Fp.mul(n, v); const i = Fp.mul(Fp.mul(nv, _2n$6), v); const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root'); return root; }; } // Other cases: Tonelli-Shanks algorithm return tonelliShanks$1(P); } // prettier-ignore const FIELD_FIELDS$1 = [ 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', 'eql', 'add', 'sub', 'mul', 'pow', 'div', 'addN', 'subN', 'mulN', 'sqrN' ]; function validateField$1(field) { const initial = { ORDER: 'bigint', MASK: 'bigint', BYTES: 'isSafeInteger', BITS: 'isSafeInteger', }; const opts = FIELD_FIELDS$1.reduce((map, val) => { map[val] = 'function'; return map; }, initial); return validateObject$1(field, opts); } // Generic field functions /** * Same as `pow` but for Fp: non-constant-time. * Unsafe in some contexts: uses ladder, so can expose bigint bits. */ function FpPow$1(f, num, power) { // Should have same speed as pow for bigints // TODO: benchmark! if (power < _0n$7) throw new Error('Expected power > 0'); if (power === _0n$7) return f.ONE; if (power === _1n$9) return num; let p = f.ONE; let d = num; while (power > _0n$7) { if (power & _1n$9) p = f.mul(p, d); d = f.sqr(d); power >>= _1n$9; } return p; } /** * Efficiently invert an array of Field elements. * `inv(0)` will return `undefined` here: make sure to throw an error. */ function FpInvertBatch$1(f, nums) { const tmp = new Array(nums.length); // Walk from first to last, multiply them by each other MOD p const lastMultiplied = nums.reduce((acc, num, i) => { if (f.is0(num)) return acc; tmp[i] = acc; return f.mul(acc, num); }, f.ONE); // Invert last element const inverted = f.inv(lastMultiplied); // Walk from last to first, multiply them by inverted each other MOD p nums.reduceRight((acc, num, i) => { if (f.is0(num)) return acc; tmp[i] = f.mul(acc, tmp[i]); return f.mul(acc, num); }, inverted); return tmp; } // CURVE.n lengths function nLength$1(n, nBitLength) { // Bit size, byte size of CURVE.n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; const nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength }; } /** * Initializes a finite field over prime. **Non-primes are not supported.** * Do not init in loop: slow. Very fragile: always run a benchmark on a change. * Major performance optimizations: * * a) denormalized operations like mulN instead of mul * * b) same object shape: never add or remove keys * * c) Object.freeze * @param ORDER prime positive bigint * @param bitLen how many bits the field consumes * @param isLE (def: false) if encoding / decoding should be in little-endian * @param redef optional faster redefinitions of sqrt and other methods */ function Field$1(ORDER, bitLen, isLE = false, redef = {}) { if (ORDER <= _0n$7) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); const { nBitLength: BITS, nByteLength: BYTES } = nLength$1(ORDER, bitLen); if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported'); const sqrtP = FpSqrt$1(ORDER); const f = Object.freeze({ ORDER, BITS, BYTES, MASK: bitMask$1(BITS), ZERO: _0n$7, ONE: _1n$9, create: (num) => mod$1(num, ORDER), isValid: (num) => { if (typeof num !== 'bigint') throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); return _0n$7 <= num && num < ORDER; // 0 is valid element, but it's not invertible }, is0: (num) => num === _0n$7, isOdd: (num) => (num & _1n$9) === _1n$9, neg: (num) => mod$1(-num, ORDER), eql: (lhs, rhs) => lhs === rhs, sqr: (num) => mod$1(num * num, ORDER), add: (lhs, rhs) => mod$1(lhs + rhs, ORDER), sub: (lhs, rhs) => mod$1(lhs - rhs, ORDER), mul: (lhs, rhs) => mod$1(lhs * rhs, ORDER), pow: (num, power) => FpPow$1(f, num, power), div: (lhs, rhs) => mod$1(lhs * invert$1(rhs, ORDER), ORDER), // Same as above, but doesn't normalize sqrN: (num) => num * num, addN: (lhs, rhs) => lhs + rhs, subN: (lhs, rhs) => lhs - rhs, mulN: (lhs, rhs) => lhs * rhs, inv: (num) => invert$1(num, ORDER), sqrt: redef.sqrt || ((n) => sqrtP(f, n)), invertBatch: (lst) => FpInvertBatch$1(f, lst), // TODO: do we really need constant cmov? // We don't have const-time bigints anyway, so probably will be not very useful cmov: (a, b, c) => (c ? b : a), toBytes: (num) => (isLE ? numberToBytesLE$1(num, BYTES) : numberToBytesBE$1(num, BYTES)), fromBytes: (bytes) => { if (bytes.length !== BYTES) throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); return isLE ? bytesToNumberLE$1(bytes) : bytesToNumberBE$1(bytes); }, }); return Object.freeze(f); } /** * Returns total number of bytes consumed by the field element. * For example, 32 bytes for usual 256-bit weierstrass curve. * @param fieldOrder number of field elements, usually CURVE.n * @returns byte length of field */ function getFieldBytesLength(fieldOrder) { if (typeof fieldOrder !== 'bigint')